如何让operator=像operator+一样接受参数的导数?

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

我不明白为什么

a = b
不像operator+那样打印出
value from operator= 5
(这似乎允许导数)。为什么它这样做而不是允许衍生品,我怎样才能让它也接受衍生品?

#include <iostream>

class A {
public:
    int value = 5;
};

class B : public A {
public:
    void operator=(const A& rhs) {
        std::cout << "value from operator= " << rhs.value << std::endl;
    }
    
    void operator+(const A& rhs) {
        std::cout << "value from operator+ " << rhs.value << std::endl;
    }
};

int main() {
    
    B a;
    B b;
    A c;
    
    std::cout << "testing operator=" << std::endl;
    std::cout << "testing with B:" << std::endl;
    a = b; // doesn't print anything
    std::cout << "testing with A:" << std::endl;
    a = c; // outputs: value from operator= 5
    
    std::cout << std::endl;
    
    std::cout << "testing operator+" << std::endl;
    std::cout << "testing with B:" << std::endl;
    a + b; // outputs: value from operator+ 5
    std::cout << "testing with A:" << std::endl;
    a + c; // outputs: value from operator+ 5
    
}
c++ polymorphism
1个回答
0
投票

B::operator=(const A& rhs)
不是复制赋值或移动赋值运算符,因此隐式定义的复制赋值运算符仍然存在,并且具有签名

B& operator=(const B&);

执行

a = b
时,该运算符在重载解析中胜过您的运算符,因为调用它时,不需要派生到基数的转换
B -> A
,这与您的赋值运算符不同。

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