如果我有两个类 A 和 B,并且我执行 A=B,则调用哪个赋值构造函数? A班的还是B班的?
有复制构造函数和赋值运算符。从
A != B
开始,将调用复制赋值运算符。
简短回答:
operator =
来自 A 类,因为您分配到 A 类。
长答案:
A=B
不起作用,因为 A
和 B
是类类型。
您可能的意思是:
A a;
B b;
a = b;
在这种情况下,将调用
operator =
的 class A
。
class A
{
/*...*/
A& operator = (const B& b);
};
以下情况将调用转换构造函数:
B b;
A a(b);
//or
B b;
A a = b; //note that conversion constructor will be called here
其中 A 定义为:
class A
{
/*...*/
A(const B& b); //conversion constructor
};
explicit
。class abc
{
public:
abc();
~abc();
abc& operator=(const abc& rhs)
{
if(&rhs == this) {
// do never forget this if clause
return *this;
}
// add copy code here
}
abc(const abc& rhs)
{
// add copy code here
}
};
Abc a, b;
a = b; // rhs = right hand side = b
因此,在左侧的对象上调用该运算符。 但请确保不要错过 if 子句。