c++ - 为什么这是 '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();
}
解决方案
您正在a
这一行的操作员内部进行修改:
x=x/ob.x;
这会修改 x。你想要的就是你所做的operator+()
。也就是说,创建一个临时对象并返回它:
OO operator/(OO ob){
OO temp;
temp.x=x/ob.x;
return temp;
}
推荐阅读
- c++ - LNK2019 及其简单英语的含义
- npm - npm install cypress vs npm install cypress --save-dev
- r - str_replace_all 使用多个条件
- react-native - 如何在我对代码进行排序并单击不同文件中的代码时显示可排序列表?
- python - 是否可以为 Tkinter 组合框列表中的特定项目着色?(在蟒蛇中)
- html - 视频 html 周围的空白
- ag-grid - AG-Grid Angular:在服务器端行模型中的列上使用多重过滤器(文本过滤器和设置过滤器),部分存储不起作用
- elasticsearch - 在 ElasticSearch 中的数组搜索中
- flutter - 是否可以将参数传递给 PreferredSizeWidget?
- android - 当页面在 ViewPager2 中不可见时如何停止视频