C++中的多插入运算符<<

Multiple insertion operator << in C++

本文关键字:运算符 插入 C++      更新时间:2023-10-16

我写了一个小代码,看看如果我使用串联插入运算符来拥有类会发生什么。

#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" ;
}

它给出了两个不同内存地址的结果,这超出了我的想象。

0x7fffdc69f6df
0x6020a0

我虽然它应该是这样的:

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

但实际上,这似乎是操作之间的"临时"MyClass。这会导致成员变量(例如,类中的int i变量)不一致。如果我希望成员变量(int i)可以一致地访问,任何人都可以对此发表评论。

您可能打算编写如下代码

#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" ;
}

输出

hello
world

观看现场演示


让我们分解一下:

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

其实和打电话一样

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

返回实例引用将启用在应用的运算符调用中调用的函数。


"但实际上,这似乎是操作之间的'临时'MyClass。

出现此问题时,您缺少使用 return *this; 语句返回当前实例。因此,访问预期返回值会导致operator<<()的第二次调用出现未定义的行为。编译器至少应该发出有关缺少return语句的警告。