c++ - 如何使operator=像operator+一样接受参数的导数?

标签 c++ polymorphism operator-overloading assignment-operator overload-resolution

我不明白为什么a = b不像operator+那样打印出来自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
    
}

最佳答案

B::operator=(const A& rhs) 不是复制赋值或移动赋值运算符,因此 implicitly-defined copy assignment operator仍然存在,并且有签名

B& operator=(const B&);

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

BA 使用此运算符的一种方法是:

B& operator=(const A& rhs) {
    std::cout << "value from operator= " << rhs.value << std::endl;
    return *this;
}

B& operator=(const B& rhs) {
    return static_cast<A&>(*this) = rhs;
}

更传统的是,A 应该有自己的用户定义的复制赋值运算符,而 B 将通过 return A::operator=(rhs) 转发给它;

关于c++ - 如何使operator=像operator+一样接受参数的导数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77816174/

相关文章:

c# - 是否有与 C# 中的 'new' 修饰符等效的 Java?

c++ - 重载类本身

c++ - 请解释一下这个好友声明是什么意思?

c++ - 将 vector 初始化为零

C# 在基类中创建派生类的实例

c++ - 为什么我要在 Constructor 中使用对 const 的引用?

java - List<Dog> 是 List<Animal> 的子类吗?为什么 Java 泛型不是隐式多态的?

c++ - 运算符重载语法说明

c++ - 如何将 Metal-Cpp 的 `id<MTLCommandQueue>` 转换为 `MTL::CommandQueue`?

c++ - 使用 optarg 在 Linux 中获取参数选项(包含空格)列表的问题