C++中的多插入运算符<<
Multiple insertion operator << in C++
我写了一个小代码,看看如果我使用串联插入运算符来拥有类会发生什么。
#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
语句的警告。
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 重载嵌套结构/类的流插入运算符
- 屏幕插入运算符<<的运算符过载问题
- 类方法的C++插入运算符
- 在设计方面:重载vector类型的类成员的插入运算符
- 类重载运算符 '<' 插入指向该对象集的共享指针时不调用
- std::map 索引运算符与插入方法的性能
- 我在C++中遇到插入运算符错误
- 基类和派生类的虚拟插入运算符重载
- 如何在 std::map<const int、int> C++ 中重载插入运算符>>?
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 如何将重载>>运算符中输入的值插入到资源库
- 插入运算符的过载与使用二传手功能相比
- Visual Studio 15:重载"<<" C++中的插入运算符
- 使用 std::stringbuf 进行缓冲的效果,同时通过插入运算符'<<'执行写入
- 为什么当我使用额外的括号而不使用运算符重载时,插入运算符在 std::cout 中给出不同的结果?
- 带有指针的重载插入/提取运算符
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 插入运算符无法使用矢量,我不知道为什么