为什么在这里调用构造函数?



我对下面的代码有疑问。在主函数中,当行:obj = 20 时会发生什么;被执行。我无法理解为什么它调用构造函数?你们中有人可以解释一下吗?

#include <iostream>
#include <string>
using namespace std;
class Int {
int x;

public:
Int(int x_in = 0)
: x{ x_in }
{
cout << "Conversion Ctor called" << endl;
}
operator string()
{
cout << "Conversion Operator" << endl;
return to_string(x);
}
};
int main()
{
Int obj(3);
string str = obj;
obj = 20;
string str2 = static_cast<string>(obj);
obj = static_cast<Int>(30);
return 0;
}

在类中没有定义赋值运算符operator =( int )。但是该类具有转换构造函数

Int(int x_in = 0)

所以在这个声明中

obj = 20;

有称为构造函数 LikeInt( 20 )将整数值转换为Int类型的对象,由于编译器生成的隐式移动赋值运算符,该对象可以分配给对象obj

缺少赋值运算符int,编译器使用它可以得到的下一个最佳赋值运算符,即隐式声明的移动赋值运算符(Int::operator=(Int&&))。要使用此运算符,需要对Int对象的右值引用,编译器使用构造函数Int::Int(int)创建该对象,即编译器将obj = 20;视为

obj.operator=(Int(20));

若要查看此处发生的情况,可以自行实现移动赋值运算符,以便在执行赋值运算符时将某些内容打印到控制台:

class Int
{
...
public:
...

Int& operator=(Int&& other)
{
std::cout << "move assignment of Int, new value: " << other.x << 'n';
x = other.x;
return *this;
}
// the following members are only declared to make sure the available
// constructors/operators are the same as in the original version of the code
Int(Int&&) = default;
Int& operator=(Int const&) = default;
Int(Int const&) = default;
};

最新更新