C++赋值构造函数

C++ Assignment Constructor

本文关键字:构造函数 赋值 C++      更新时间:2023-10-16

如果我有两个类A和B,并且我做A=B,那么调用哪个赋值构造函数?A班的还是B班的?

有复制构造函数和赋值运算符。由于A != B,将调用复制分配运算符。

简短回答:operator =来自A级,因为你要分配给A级。

长答案:

A=B将不起作用,因为AB是类类型。

你的意思可能是:

A a;
B b;
a = b;

在这种情况下,将调用class Aoperator =

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
};

请注意,这引入了B和A之间的隐式转换。如果不需要,可以将转换构造函数声明为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子句