首页 > 解决方案 > 为什么这是 'a' = 2,而不是 7?

问题描述

我正在重载运算符'/'。当我将对象“a”与对象“b”(在 main 下)相除时,对象“a”更改为 2,而不是等于 7,就像之前的除法一样。这是一个错误吗?如果不是,为什么 'a'=2 而不是 7?

#include <iostream> 
using namespace std;
class OO{
  int x;
  int y;
  public:
         OO(){x=y=0;}
         OO(int i, int j){x=i;y=j;}
         OO operator+(OO ob){
                         OO temp;
                         temp.x=x+ob.x;
                         return temp;
                         }
         OO operator=(OO ob){
                        x=ob.x;
                        return *this;
                        } 
         OO operator/(OO ob){
                        x=x/ob.x;
                        return *this;
                        }
         OO operator++(){
                         OO temp;
                         temp.x=++x;
                         return temp;

                         }                                            
         void show(){

              cout<<x<<endl;

              }                             

  };


int main() {
OO a(6,2);
OO b(3,2);
b.show();
a.show();
OO c = a + a;
c.show();
++a;
a.show();
c = a / b;
a.show();//why is this 'a' = 2, instead of 7?
c.show();
c=b=a;
c.show();
}

标签: c++

解决方案


您正在a这一行的操作员内部进行修改:

x=x/ob.x;

这会修改 x。你想要的就是你所做的operator+()。也就是说,创建一个临时对象并返回它:

OO operator/(OO ob){
    OO temp;
    temp.x=x/ob.x;
    return temp;
}

推荐阅读