【发布时间】:2014-11-18 04:50:05
【问题描述】:
我编写了一个小代码来看看如果我使用系列插入运算符来拥有类会发生什么。
#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) 可以持续访问,任何人都可以向 cmets 提供此信息。
【问题讨论】:
-
这段代码还能编译吗?运算符函数不返回值。
-
看起来你对
mc << "hello" << "world" ;的实际作用有一些严重的误解。您的问题毫无意义,一切都按预期进行。 -
你好,马蒂!代码可以编译。我可能不太了解运算符重载的概念。这就是我尝试编写小代码来弄清楚的原因。当我将 i++ 添加到实现 MyClass& MyClass::operator
-
@Chiat-ChhànÂng 查看我的回答。 Clarify your question!
标签: c++ class operator-overloading insertion