当赋值A=B时,是调用A的赋值运算符还是B的赋值运算符?

问题描述 投票:0回答:2

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

c++ copy-constructor assignment-operator
2个回答
6
投票

有复制构造函数和赋值运算符。从

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

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


0
投票
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 子句。

© www.soinside.com 2019 - 2024. All rights reserved.