我正在努力处理运算符重载,因为我希望它允许链接
class A{
int a;
public:
void doSomething(char *str);
A operator<<(char *str);
}
所以我有这个类(class),我能做的就是获取一个字符串并做一些事情,这对这个问题并不重要。
我现在能做的是
A *counter = new A();
counter->doSomething("hello");
如果我实现重载的移位运算符
A A::operator<<(char *str)
{
this->doSomething(str);
return this;
}
我可以这样写
A *counter = new A();
(*counter) << "hello";
我希望我没有在这里犯错,因为现在我想知道如何允许链接
(*counter) << "hello" << "test";
我知道通过链接它会做到这一点
(*counter).operator<<("hello" << "test");
这显然没有任何意义,因为有两个字符串/字符数组 但我知道有办法做到这一点。我用谷歌搜索,但每个问题都只是关于将相同类型的实例链接在一起
然后我尝试将两个参数放入函数并将其添加为 friend ...我不确定但也许我必须创建一个类型为 char*
或的新重载运算符流对象并将其作为 A
的友元?
感谢您帮助我,我想应该有一个我现在看不到的简单答案。
最佳答案
您需要返回对*this
的引用,因此您的返回类型需要是A&
:
A& operator<<(char *str)
{
this->doSomething(str); // as before
return *this; // return reference to this instance.
}
关于c++ - 重载移位运算符 << 以允许链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17782879/