执行加法时修改第一类对象
First class object is modified when doing a addition
下面的代码给出了正确的加法输出,在执行后更改了第一个对象 b 的 x 值。
class numbers{
public:
int x;
numbers(int i1){
x = i1;
}
numbers operator+ (numbers num){
x = x + num.x;
return(x);
}
};
int main(){
numbers a (2);
numbers b (3);
numbers c (5);
numbers d (7);
cout << a.x << b.x << c.x << d.x << endl; // returns 2357
numbers final (100); //this value won't be shown
final = a+b+c+d;
cout << a.x << b.x << c.x << d.x << endl; // returns 5357
cout << final.x; //returns 17 (2+3+5+7)
system("pause");
}
问题是,这个加法类究竟是如何工作的?我的意思是,为什么对象 a 中的 x 被修改了?我虽然只有来自最终对象的 x 会被修改。
谢谢:)
对 operator+ 的调用就像任何其他成员函数调用一样。 a + b
翻译为a.operator+(b)
。因此,在这种情况下x = x + num.x;
行实际上是分配给a.x
。要实现您想要的,您需要用新值填充新数字,即
numbers operator+ (numbers num) const {
return numbers(x + num.x)
}
还要注意 const - 当你犯了这个错误时,它会给你一个编译错误。
您编码的运算符 + 实际上正在执行您对运算符 += 的期望
运算符 + 应返回保存计算值的对象编号,而不是修改当前对象。
这里有一些准则
你的operator+
会改变this
,因为这是你定义它的方式。或者,您可以尝试
numbers operator+( const numbers& num ) {
numbers ret( this->x ); // constract a local copy
ret.x += num.x;
return ret;
}
相关文章:
- 如何创建从同一类继承的不同对象的向量
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 同一类的两个对象相互引用
- 打印同一类中的 3 个对象
- 在 c++ 中,同一类的一个对象如何分配给同一类的另一个对象?
- 如何在C++中将类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- 如何重载"<"运算符以比较同一类的对象?
- 将来自类的对象用作另一类C 类的对象
- 修改对象也会修改同一类的所有其他对象
- 在另一类中使用受保护的破坏者删除对象
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- 如何为同一类对象的成员函数保留单独的变量副本?
- 如何将成员函数用于同一类的不同对象
- 如何使用nullptr初始化同一类对象的静态指针数组?
- 一类应管理其实例化对象
- 如何重载赋值运算符以满足 ob1=ob2=ob3(ob1,ob2,ob3 是同一类的对象)
- C++:按值将对象传递给同一类的成员函数
- 有什么方法可以测试来自同一类的两个作业对象吗
- C++类构造函数使用指向同一类对象的指针
- C++如何共享同一类对象中的公共元素