超载预先插入操作员未显示正确的结果
overloading pre-increment operator not showing correct result
我已经使用朋友函数超载了预入口操作员。在超载的朋友函数中,变量的值显示正确。但是该值未显示在显示功能中,为什么?
#include <iostream>
using namespace std;
class Rectangle {
public:
int breadth;
public:
void read();
void display();
friend void operator ++(Rectangle r1);
};
void Rectangle::read()
{
cout << "Enter the breadth of the Rectangle: ";
cin >> breadth;
}
void operator++(Rectangle r1)
{
++r1.breadth;
cout<<r1.breadth<<endl; //correct result
}
void Rectangle::display()
{
cout<<breadth<<endl; // not showing pre-incremented value, why ???
}
int main()
{
cout<<"Unary Operator using Friend Function n";
Rectangle r1;
r1.read();
++r1;
cout << "n breadth of Rectangle after increment: ";
r1.display();
return 0;
}
您的 operator ++
按值将 Rectangle
对象采用,这意味着它接收其操作数的 copy 。然后,它尽职尽责地递增副本的breadth
成员,将其打印出去,然后在副本结束时丢弃。
您需要通过参考来进行参数:
friend void operator ++(Rectangle &r1)
{
++r1.breadth;
}
还要注意,使用成员函数而不是免费功能过载的一元运算符非常普遍。这样使用,您不会遇到这个问题:
class Rectangle
{
// ...
public:
void operator++ ()
{
++breadth;
}
// ...
};
一些一面评论:
operator++
通常返回对其操作数的引用,以模仿内置运算符。就像可以为int i
执行++ ++ i
一样,对于用户定义的类型r
也应该进行++ ++ r
。在实践中,只有在a)编写类型的类型时才能使用运算符过载,或者b)您正在编写特定于域的语言。我无法直观地解释矩形,并且最好作为命名成员函数完成。您如何判断
++r
是否会增加宽度,高度,或两者兼有,或者将矩形移到右侧,或者...?
相关文章:
- 密码登录程序将永远循环并显示不正确的结果
- 这两个代码片段相似,但显示的结果不同
- 代码未在联机编译器上显示结果
- 为什么 Lisp 中 1000 阶乘的计算如此之快(并显示正确的结果)?
- lambda 函数未显示正确的结果
- 回复计划游戏结果不会显示
- 谷歌基准测试结果中显示的时间没有意义
- 我的代码厨师提交显示错误的结果
- 如何从2D数组为QHeightMapSurfaceDataProxy创建高度图以显示2D傅立叶变换结果
- 声明"使用命名空间 C;"对于证明 [namespace.udir]/3 中的示例中显示的结果至关重
- 如何在 for 循环中显示一个结果
- 我无法弄清楚我的代码未显示预期结果的问题
- 在这种情况下,GCC 和 clang 是否显示与 Visual Studio 相同的结果,关于语言链接?
- 我的循环超时并且不显示结果
- 使用 C++ 中的运算符重载显示不正确的结果
- 在 for 循环中仅显示序列的最后一个结果
- 在单击QT中单击图像时,尝试立即显示用户编辑操作的结果
- C 可执行文件从浏览器下载而不是显示结果
- OpenGL -- 多个 glDrawArrays() 调用仅显示第一个的结果
- 为什么程序显示的值大于结果或垃圾值