超载预先插入操作员未显示正确的结果

overloading pre-increment operator not showing correct result

本文关键字:结果 显示 插入 操作员 超载      更新时间:2023-10-16

我已经使用朋友函数超载了预入口操作员。在超载的朋友函数中,变量的值显示正确。但是该值未显示在显示功能中,为什么?

#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是否会增加宽度,高度,或两者兼有,或者将矩形移到右侧,或者...?