过载运算符<<允许链接

rae*_*rne 0 c++ operator-overloading chaining

我正在努力与运算符重载,因为我希望它允许链接

class A{
 int a;
public:
 void doSomething(char *str);
 A operator<<(char *str);
}
Run Code Online (Sandbox Code Playgroud)

所以我有这个课,我能做的就是拿一个字符串做一些事情,这对这个问题并不重要.

我现在能做的是

A *counter = new A();
counter->doSomething("hello");
Run Code Online (Sandbox Code Playgroud)

如果我实现了重载的移位运算符

A A::operator<<(char *str)
{
  this->doSomething(str);
  return this;
}
Run Code Online (Sandbox Code Playgroud)

我可以像这样写

A *counter = new A();
(*counter) << "hello";
Run Code Online (Sandbox Code Playgroud)

我希望我在这里没有犯错,因为现在我想知道我怎么能允许链接

(*counter) << "hello" << "test";
Run Code Online (Sandbox Code Playgroud)

我知道通过链接可以做到这一点

(*counter).operator<<("hello" << "test");
Run Code Online (Sandbox Code Playgroud)

这显然没有任何意义,因为有两个字符串/字符串数组但我知道有一种方法可以做到这一点.我用谷歌搜索它,但每个问题只是关于将相同类型的实例链接在一起

然后我尝试将两个参数放入函数并将其添加为朋友...我不确定但是我可能需要使用类型char*或流对象创建一个新的重载运算符并使其成为朋友A

感谢您的帮助,我想应该有一个我现在看不到的简单答案.

jua*_*nza 5

您需要返回引用*this,因此您的返回类型必须是A&:

A& operator<<(char *str)
{
  this->doSomething(str); // as before
  return *this;           // return reference to this instance.
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,你*可以*按价值回报,连锁电话就好了.但您可能想解释为什么您通常*希望*通过引用返回. (2认同)