Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 过载换档操纵器_C++_Operator Overloading_Chaining - Fatal编程技术网

C++ 过载换档操纵器

C++ 过载换档操纵器,c++,operator-overloading,chaining,C++,Operator Overloading,Chaining,我正在与操作符重载作斗争,因为我希望它允许链接 class A{ int a; public: void doSomething(char *str); A operator<<(char *str); } (*counter) << "hello" << "test"; 如果我实现重载移位运算符 A A::operator<<(char *str) { this->doSomething(str); return this

我正在与操作符重载作斗争,因为我希望它允许链接

class A{
 int a;
public:
 void doSomething(char *str);
 A operator<<(char *str);
}
(*counter) << "hello" << "test";
如果我实现重载移位运算符

A A::operator<<(char *str)
{
  this->doSomething(str);
  return this;
}
我能这样写

A *counter = new A();
(*counter) << "hello";
我希望我在这里没有犯错误,因为现在我想知道我怎么能允许链接

class A{
 int a;
public:
 void doSomething(char *str);
 A operator<<(char *str);
}
(*counter) << "hello" << "test";
我知道用链子拴住它可以做到这一点

(*counter).operator<<("hello" << "test");
这显然没有任何意义,因为有两个字符串/字符数组 但我知道有办法做到这一点。我用谷歌搜索了一下,但每个问题都只是关于将同一类型的实例链接在一起

然后我尝试将两个参数放入函数中,并将其添加为友元。。。我不确定,但也许我必须用char*类型创建一个新的重载运算符,或者创建一个stream对象,并将其作为一个


谢谢你的帮助,我想应该有一个简单的答案,我现在还没有看到。

操作符你需要返回一个对*的引用,所以你的返回类型需要是&:

使“计数器”成为指针,而不是对象。要在上使用运算符,可以使用

(*counter) << "hello" 

此外,我建议您重新考虑重载运算符。虽然一开始这似乎是一个很酷的想法,但很容易产生难以理解和维护的代码。

在你的问题中有两个错误的假设,我想澄清一下


当您想调用operator*A Well时,您可以通过value和chain调用返回。但是你可能想解释为什么你通常想通过引用返回。当你想呼叫Operatories时,这是可能的,但确实很奇怪。我不建议对左手边的任何类型的指针重载运算符。只是因为它看起来很奇怪。您的运算符最好使用const char*。
A& operator<<(char *str)
{
  this->doSomething(str); // as before
  return *this;           // return reference to this instance.
}
A *counter = new A();
(*counter) << "hello" 
A *counter = new A();
(*counter) << "hello";
(*counter) << "hello" << "test";
(*((*counter) << "hello")) << "test";
A << "hello" << "test";
A.operator<<("hello" << "test");
A.operator<<("hello").operator<<("test");
( A.operator<<("hello") ).operator<<("test");
A& operator<<(char *str)
{
    this->doSomething(str);
    return *this;
}