考虑下面的代码,
Calling A
应该被打印出来吗?因为a
的运行时类型是B
,所以虚函数调用应该导致调用B::operator=
(因为虚函数调用由左操作数确定)。#include <iostream>
class A
{
public:
virtual A& operator=(const A& a_) { std::cout << "Calling A" << std::endl; }
};
class B : public A
{
public:
virtual B& operator=(const B& b_) { std::cout << "Calling B" << std::endl; }
};
int main() {
B b1;
B b2;
A& a = b1;
a = b2; // Prints "Calling A", should be "Calling B"?
return 0;
}
A::operator=(const B& b_)
,只有A::operator=(const A& a_)
。 - Mohit JainCalling B
消息,你应该在类B中尝试这样做:virtual B& operator=(const A& b_) override { std::cout << "Calling B" << std::endl; return *this; }
。 - αλεχολυτoperator=
时,你也应该总是使用return *this
。 - PC Luddite