c++ - 为什么 cout << 不能与重载的 * 运算符一起工作?

标签 c++ operator-overloading

我正在创建我的第一个类,主要由 Overland 的 C++ Without Fear 指导。我让重载的 friend ostream operator<< 工作正常。我还重载了 * 运算符,并且工作正常。当我尝试直接输出 * 运算符的结果时不起作用:

BCD bcd(10);  //bcd is initialised to 10
BCD bcd2(15); //bcd2 is initialised to 15
cout << bcd;  //prints 10
bcd2 = bcd2 * 2; //multiplies bcd2 by 2
cout << bcd2; //prints 30

cout << bcd * 2 //SHOULD print 20, but compiler says
//main.cpp:49: error: no match for 'operator<<' in 'std::cout << BCD::operator*(int)(2)'

有关信息,这是我的原型(prototype):

BCD operator*(int z);
friend ostream &operator<<(ostream &os, BCD &bcd);

据我所知,operator* 返回 BCD,因此 operator<< 应该能够打印它。请帮忙!

最佳答案

发生的事情是bcd * 2正在生成临时 BCD , 无法绑定(bind)到 BCD & .尝试更换 <<具有以下之一的运算符:

friend ostream &operator<<(ostream &os, const BCD &bcd);

friend ostream &operator<<(ostream &os, BCD bcd);

甚至

friend ostream &operator<<(ostream &os, const BCD bcd);

第一个可行,因为明确允许将临时变量绑定(bind)到常量引用,这与绑定(bind)到非常量引用不同。其他的通过复制临时变量来工作。

编辑: 如评论中所述 - 在大多数情况下更喜欢 const & 版本,因为在流式运算符中修改对象对于使用您的类的任何人来说都是令人惊讶的。让它编译可能需要添加 const在适当的地方声明你的类成员函数。

关于c++ - 为什么 cout << 不能与重载的 * 运算符一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/451983/

相关文章:

c++ - Windows Media Foundation 录制音频

c++ - 以非顺序顺序在 vector 中分配值

c++ - 如何专门化模板模板的功能?

c++ - "Ambigous"等效转换 - 我可以让编译器只选择任何一个吗?

c++ - 类模板上的关系运算符

c++ - 如何确定我们是否在主线程中运行?

c++ - 学习 C++ 和 SDL- 以下是否会产生内存泄漏?

c++枚举作为函数中的参数并在另一个文件中调用该函数

c++ - 另外重载的代码没有效果

c# - 如何在 C# 中为枚举重载运算符?