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

发布于 2024-12-26 02:55:00 字数 54 浏览 1 评论 0原文

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

If I have two classes A and B and I do A=B which assignment constructor is called? The one from class A or the one from class B?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

新人笑 2025-01-02 02:55:00

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

简短答案:来自 A 类的 operator =,因为您要分配给 A 类。

长答案:

A=B 不起作用,因为 A > 和 B 是类类型。

您可能的意思是:

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 之间引入隐式转换。如果您不希望这样做,可以将转换构造函数声明为显式

There's copy constructor and there's assignment operator. Since A != B, the copy assignment operator will be called.

Short answer: operator = from class A, since you're assigning to class A.

Long answer:

A=B will not work, since A and B are class types.

You probably mean:

A a;
B b;
a = b;

In which case, operator = for class A will be called.

class A
{
/*...*/
   A& operator = (const B& b);
};

The conversion constructor will be called for the following case:

B b;
A a(b);

//or

B b;
A a = b; //note that conversion constructor will be called here

where A is defined as:

class A
{
/*...*/
    A(const B& b); //conversion constructor
};

Note that this introduces implicit casting between B and A. If you don't want that, you can declare the conversion constructor as explicit.

尤怨 2025-01-02 02:55:00
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 子句。

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

So the operator is called on the object on the left hand side.
But make sure you do not miss the if clause.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文