C++ 多重插入运算符<&书信电报;在C++;

C++ 多重插入运算符<&书信电报;在C++;,c++,class,operator-overloading,insertion,C++,Class,Operator Overloading,Insertion,我写了一个小代码,看看如果我使用系列插入操作符来拥有类会发生什么 #include <iostream> using namespace std; class MyClass { public: int i; MyClass & operator<< ( const string & ); } ; MyClass& MyClass::operator<< ( const string &

我写了一个小代码,看看如果我使用系列插入操作符来拥有类会发生什么

#include <iostream>
using namespace std;


class MyClass
{
    public:
        int i;
        MyClass & operator<< ( const string &  );

} ;

MyClass& MyClass::operator<< ( const string &  )
{
    cout << this << endl ;
}

int main()
{
    MyClass mc;

    mc << "hello" << "world" ;

}
我想应该是这样的:

(( mc << "hello" ) << "world" );

((mc您可能打算编写如下代码

#include <iostream>
using namespace std;

class MyClass {
    public:
        int i;
        MyClass & operator<< ( const string &  );
} ;

MyClass& MyClass::operator<< ( const string & str) { // Note the parameter symbol
    cout << str << endl ; // Note usage of the parameter symbol "str", "this" is not 
                          // what you actually want here, it just outputs the address 
                          // of the class instance
    return *this; // Return the instance reference properly to allow chaining of
                  // subsequent operator<<() calls
}

int main() {
    MyClass mc;

    mc << "hello" << "world" ;
}


让我们来分析一下:

 mc << "hello" << "world";

mc此代码是否编译?运算符函数不返回值。看起来您对什么
mc Hello Matti有一些严重的误解!代码可以编译。我可能不太理解运算符重载的概念。这就是我尝试编写小代码以找出原因的原因。添加I++时代码失败进入实现MyClass&MyClass::operator@Chiat-请看我的答案。
hello
world
 mc << "hello" << "world";
 mc << "hello";
 mc << "world";