疑点在代码中测试赋值运算符的使用

Doubts in a code to test the use of assignment operator

本文关键字:赋值运算符 测试 代码      更新时间:2023-10-16

我正在写一个代码来测试赋值操作符和复制构造函数的使用。代码如下:

#include <iostream>
#include <algorithm>
using namespace std;
class fun {
  int i;
  public:
         fun():i(1) {i=1;cout<<"in: consn";}
         ~fun() {cout<<"in: desn";}
         fun& operator=(fun b) {
              cout<<"in: assignOpn";
              swap(this->i, b.i);
              return *this;
         }
         fun(fun& b) {
              cout<<"in: copy consn";
              b.i = this->i;
         }
         void print() {
              cout<<i<<endl;
         }
};
main() 
{
   fun A;
   fun B;
   B = A;
   A.print();
}

下面是代码的输出:

:缺点

:缺点

in: copy cons

: assignOp

des

:

-1216991244

des

:des

:

现在,关于输出,有两件事我不明白。

首先,为什么代码在复制构造函数中运行?其次,为什么'i'的值被打印为垃圾而不是'1'?

我是一个新手,所以如果我的疑问很明显,请原谅。

B = A;

这会导致调用赋值操作符。您在输出中看到copy cons的原因是因为您的赋值操作符按值接受它的参数。因此,A被复制到赋值操作符函数中,这需要使用复制构造函数。

复制构造函数和复制赋值操作符通常通过const引用获取实参。

你得到垃圾值的原因是你把这行写反了:

b.i = this->i;

应该是:

this->i = b.i;

否则,您的复制构造函数将this->i的不确定值复制到您正在复制的对象中。

首先,为什么代码在复制构造函数中运行?

为赋值操作符复制实参时调用复制构造函数。您正在按值传递参数给赋值操作符,而不是通过引用:

fun& operator=(fun b)
不是

fun& operator=(const fun& b)

其次,为什么'i'的值被打印为垃圾而不是'1'?

在你的复制构造函数中,你赋值的方式是错误的:

b.i = this->i;

代替

this->i = b.i;