我不明白为什么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
,与赋值运算符不同。
让 B
和 A
使用此运算符的一种方法是:
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/