疑点在代码中测试赋值运算符的使用
Doubts in a code to test the use of assignment operator
我正在写一个代码来测试赋值操作符和复制构造函数的使用。代码如下:
#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;
相关文章:
- 重载Singly Linked List中的赋值运算符
- 使用赋值运算符重载从类中返回jobject
- 标准库类型的赋值运算符的引用限定符
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 基类和派生类的多态赋值运算符
- 为用户定义的类正确调用复制构造函数/赋值运算符
- CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc
- 为什么初始化时没有调用重载赋值运算符?
- 赋值运算符重载和自赋值
- C++矢量复制构造函数和赋值运算符是否也复制保留空间?
- Qt PL/SQL - 赋值运算符 - 字符串缓冲区太小
- 对 r 值使用移动赋值运算符时的异常
- 由于没有使用赋值运算符,映射的值是如何初始化的?
- 默认赋值运算符如何在实际 STL 中实现
- 使用赋值运算符复制 std::vector
- VC++ Express 2010 在模板化类的重载赋值运算符的自赋值测试中出错
- 疑点在代码中测试赋值运算符的使用
- 默认复制赋值运算符未通过is_copy_assignable测试