#include<iostream>
using namespace std;
class A {
public:
virtual void f() {
cout << "af" << endl;
}
void g() {
cout << "ag" << endl;
}
};
class B :public A {
public:
void f() {
cout << "bf" << endl;
}
void g() {
cout << "gf" << endl;
}
};
int main() {
A* p;
B b;
p = &b;
p->f();
p->g();
cout << "------------" << endl;
if ((dynamic_cast<B*>(p)) == NULL) {
cout << "error" << endl;
}
else
{
B* son = dynamic_cast<B*>(p);
p->f();
p->g();
cout << "---------" << endl;
son->f();
son->g();
}
return 0;
}
运行结果为:
bf
ag
------------
bf
ag
---------
bf
gf
结论:
1.父类指针指向子类对象时,对于同名函数,如果子类重写了父类的虚函数,则调用子类的虚函数,否则仍然调用父类的同名函数。
2.dynamic_cast在向下强转(父类转子类)时正常。