【发布时间】:2020-05-28 19:20:07
【问题描述】:
在 C++ 中有没有办法将插入运算符用于类方法?
这个operator<< 重载正在工作:
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
Complex() {};
~Complex() {};
};
我可以这样做:
int main()
{
Complex* o = new Complex();
std::cout << "This is test: " << *o << "." << std::endl; // => This is test: test overload.
}
我知道流操纵器,像这样:
std::ostream& welcome(std::ostream& out)
{
int data = 1;
out << "WELCOME " << data << "\r\n";
return out;
}
int main()
{
std::cout << "Hello " << welcome; // => "Hello WELCOME 1\r\n"
}
如何将welcome 方法放入Complex 类中,然后如何从cout 调用它(请注意welcome 方法必须访问一些类成员变量)?
我的审判:
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
std::ostream& welcome(std::ostream& out) {
out << "WELCOME " << data << "\r\n";
return out;
}
Complex() { data = 1; };
~Complex() {};
private:
int data;
};
int main()
{
Complex* o = new Complex();
std::cout << "This is test2: " << o->welcome << std::endl; // compile error
}
【问题讨论】:
-
请出示真实代码。你的“正常”重载是一个成员函数,不能像这样工作
-
mymethod可以返回一个字符串,然后您可以执行std::cout << c.mymethod() << " then other stuff"。请澄清,它不是很清楚你的问题是什么 -
您的程序的预期输出究竟是什么?
-
你可以编写一个自定义的操纵器来实现这样的效果。 accu.org/index.php/journals/1769
-
您不必将其留在那里作为历史记录,您也不必在您的问题中添加“更新”。如果有人想查看编辑历史记录,可以在这里进行:stackoverflow.com/posts/62072866/revisions
标签: c++ iostream ostream insertion