C++ 中 operator= 的奇怪行为

nup*_*ler 7 c++ inheritance assignment-operator

我有一个基类 A 和两个派生类 B 和 C。 B 定义了 = 运算符,将基类 A 作为参数。

在类 B 上调用 = 时,有时会调用基类 A 的运算符而不是 B 中的运算符。

class A {
        public:

        void operator=(A &) {
                printf("A =\n");
        };
};

class B : public A {

        public:

        void operator=(A &s) {
                printf("B =\n");
        };
};

class C : public A {
};

int main()
{
        B b1, b2;
        C c;

        b1 = b2;
        b1 = c;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

A =
B =
Run Code Online (Sandbox Code Playgroud)
  • 为什么第一个赋值不调用 B::operator=()?

  • 为什么第二个赋值不调用 A::operator=() ,因为它也是从 A 派生的?

  • 我该怎么做才能让 B::operator=() 每次都被调用?

当我看到这一点时,我感到非常惊讶。我注意到它只是因为我删除了 A 类中的 operator=() ("operator=() = delete"),导致编译器错误。

Igo*_*nik 10

B::operator=不是复制赋值运算符。除了您提供的,还有一个隐式定义的复制赋值运算符,它等效于

B& operator=(const B& other) {
  A::operator=(other);
  return *this;
}
Run Code Online (Sandbox Code Playgroud)

这个操作符不打印任何东西,但它调用基类上的赋值,然后打印A=.

b1 = b2调用此复制赋值运算符。b1 = c调用B::operator=(A&)因为C不是B.

如果您希望您的运算符被调用,请使用上面显示的签名定义一个复制赋值运算符,而不是其他重载,或者除了其他重载之外。