我正在创建我的第一个类,主要由 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/