提问人:Daniel 提问时间:5/29/2020 最后编辑:Daniel 更新时间:5/29/2020 访问量:214
类方法的 C++ 插入运算符
C++ insertion operator for class method
问:
在 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
我的试用:
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
}
答:
2赞
463035818_is_not_an_ai
5/29/2020
#1
选择不同重载的一种简单方法是使用不同的类型。<<
#include <iostream>
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
struct extra_info {
const Complex& parent;
extra_info(const Complex& p) : parent(p) {}
friend std::ostream& operator<<(std::ostream& out, const extra_info& ei){
int i = 1;
out << "extrainfo " << i;
return out;
}
};
extra_info extrainfo() {
return {*this};
}
Complex() {};
~Complex() {};
};
int main() {
Complex c;
std::cout << c << "\n";
std::cout << c.extrainfo();
}
输出:
test overload
extrainfo 1
我想在你的真实代码中,你正在使用成员。因此,帮助程序类型必须包含对实例的引用。Complex
评论
0赞
Swift - Friday Pie
5/29/2020
嗯。。我们可以通过使用非递归操纵器来摆脱警告吗?不像我们在嵌套类的情况下需要一个参数。或者可以删除参数的名称ei
0赞
Daniel
5/29/2020
c.welcome(std::cout)
在我的机器上编译失败:“错误:无法将'std::ostream {aka std::basic_ostream}'左值绑定到'std::basic_ostream&&'”
0赞
463035818_is_not_an_ai
5/29/2020
@Swift-FridayPie 对不起,我不明白。我没有收到任何警告,也没有递归
0赞
463035818_is_not_an_ai
5/29/2020
@Daniel对不起,你把代码改得很快,我懒得仔细写答案,我的错,我会把它删除
0赞
Daniel
5/29/2020
@idclev463035818:我对你的观点很感兴趣:这个extrainfo解决方案在理论上比创建一个字符串流并将其返回给cout更好(运行速度更快)?
评论
mymethod
可以返回一个字符串,然后你可以做.请澄清一下,它并不清楚你的问题是什么std::cout << c.mymethod() << " then other stuff"