C++ Assignment构造函数

Ker*_*rry 3 c++ copy-constructor assignment-operator

如果我有两个A和B类,我做A = B,调用赋值构造函数?A级或B级的那个?

Luc*_*ore 6

有复制构造函数和赋值运算符.因为A != B,将调用复制赋值运算符.

简短的回答:operator =来自A班,因为你要分配到A班.

答案很长:

A=B将无法正常工作,因为AB是类类型.

你可能意味着:

A a;
B b;
a = b;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,operator =对于class A将被调用.

class A
{
/*...*/
   A& operator = (const B& b);
};
Run Code Online (Sandbox Code Playgroud)

转换构造函数将被调用下面的情况:

B b;
A a(b);

//or

B b;
A a = b; //note that conversion constructor will be called here
Run Code Online (Sandbox Code Playgroud)

其中A定义为:

class A
{
/*...*/
    A(const B& b); //conversion constructor
};
Run Code Online (Sandbox Code Playgroud)

请注意,这会在B和A之间引入隐式转换.如果您不希望这样,则可以将转换构造函数声明为explicit.