【发布时间】:2012-04-01 14:33:31
【问题描述】:
我知道虚函数和运行时调用的基本概念。但我试过了 运行一些让我困惑的代码
class A {
public:
A& operator=(char) {
cout << "A& A::operator=(char)" << endl;
return *this;
}
virtual A& operator=(const A&) {
cout << "A& A::operator=(const A&)" << endl;
return *this;
}
};
class B : public A {
public:
B& operator=(char) {
cout << "B& B::operator=(char)" << endl;
return *this;
}
virtual B& operator=(const B&) {
cout << "B& B::operator=(const B&)" << endl;
return *this;
}
};
int main() {
B b1;
B b2;
A* ap1 = &b1;
A* ap2 = &b1;
*ap1 = 'z';
*ap2 = b2;
}
运行这个程序给我以下输出:-
A& A::operator=(char) //expected output
A& A::operator=(const A&) //Why this Output? in case of *ap2 = b2;
b2 是 B 类型的对象,但它仍然是虚拟的 A& operator=(const A&)
而不是虚拟的B& operator=(const B&)。为什么会这样?
【问题讨论】:
标签: c++ copy-constructor