class A {
private:
A& operator=(const A&);
};
class B : public A {
public:
B& operator=(const A&) {
return *this;
}
};
int main() {
B b1;
B b2;
b1 = b2;
return 0;
}
这会导致编译错误:
test.cpp: In member function 'B& B::operator=(const B&)':
test.cpp:16:5: error: 'A& A::operator=(const A&)' is private
test.cpp:19:20: error: within this context
test.cpp: In function 'int main()':
test.cpp:31:7: note: synthesized method 'B& B::operator=(const B&)'
first required here
Build error occurred, build is stopped
由于 B::operator=(A&) 具有非标准签名,因此编译器生成它自己的 B::operator=(B&),它(尝试)调用私有(private)的 A::operator(A&)。
有什么方法可以让编译器对 B 参数也使用 B::operator=(A&) 吗?
最佳答案
当然。只需自己定义运算符并将调用转发给 operator=(const A&)
。
class B : public A {
public:
B& operator=(const A&) {
return *this;
}
B& operator=(const B& other) {
return *this = static_cast<const A&>(other);
}
};
关于c++ - 具有派生类型参数的赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7358134/