多个插入算子<<在C ++中

时间:2014-11-18 04:50:06

标签: c++ class operator-overloading insertion

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

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

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

1 个答案:

答案 0 :(得分:1)

你可能想写一些代码如下

#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

请参阅LIVE DEMO


让我们打破这个:

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

实际上与调用

相同
 mc << "hello";
 mc << "world";

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


  

&#34;但实际上,它似乎是一个临时的&#34;操作之间的MyClass。&#34;

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