我了解虚拟功能和运行时调用的基本概念。但我想 运行某些部分的代码,让我感到困惑有人可以解释这个虚拟功能的行为?
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&)
。这是为什么?
Chalesworth的有效形式,从而是,该函数调用,而不是种中的指针类型的事项对象是指向的指针,哪个实际发生在虚函数的情况下?因为这里ap2是A的指针类型,但指向B类型的对象?我在哪里错了? – Invictus 2012-03-31 19:25:35
@Ritesh:在'* ap2 = b2'行,'* ap2'的编译时类型是'A'。因此,编译器只能考虑在“A”呈现的接口中存在的(虚拟)成员函数。 – 2012-03-31 19:26:59