为什么不计算<< 使用重载的 * 运算符?

发布于 2024-07-12 03:52:44 字数 728 浏览 5 评论 0 原文

我正在创建我的第一个课程,主要以 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<< 应该能够打印它。 请帮助!

I'm creating my first class, mainly guided by Overland's C++ Without Fear. I've made the overloaded friend ostream operator<<, which works fine. I've also overloaded the * operator, and that works fine. What doesn't work is when I try to output the result of the * operator directly:

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

For info, here are my prototypes:

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

As far as I can tell, operator* returns a BCD, so operator<< should be able to print it. Help please!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

热鲨 2024-07-19 03:52:45

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

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

or

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

甚至

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

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

编辑:
正如评论中所指出的 - 更喜欢 const & 在大多数情况下,版本,因为修改流操作符中的对象会让任何使用你的类的人感到惊讶。 对其进行编译可能需要在适当的情况下向类成员函数添加 const 声明。

What's happening is that bcd * 2 is generating a temporary BCD, which cannot bind to a BCD &. Try replacing the << operator with one of these:

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

or

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

or even

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文