5

我正在创建我的第一堂课,主要由 Overland 的 C++ without Fear 指导。我已经使重载的朋友 ostream 运算符<<,它工作正常。我还重载了 * 运算符,并且效果很好。当我尝试直接输出 * 运算符的结果时不起作用:

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)'

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

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

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

4

1 回答 1

12

正在发生的事情bcd * 2是生成一个临时的BCD,它不能绑定到一个BCD &. 尝试用以下<<之一替换运算符:

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

或者

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

甚至

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

The first one works, since binding a temporary variable to a constant reference is explicity allowed, unlike binding to a non-const reference. The other ones work by making a copy of the temporary variable.

Edit: As noted in the comments - prefer the const & version in most cases, since modifying an object in a streaming operator will be surprising to anyone using your class. Getting this to compile may require adding const declarations to your classes member function where appropriate.

于 2009-01-16T21:03:53.383 回答