常见使用方法:A *a = new B(); a->func();
若func()为虚函数,则优先调用B中的func()
若func()为不为虚函数,则优先调用A中的func()
若A *c = *a;c->func();同上
若A d = *a;d.func();则只执行A中的func() 原因:强制转化为A对象的空间,和B无关。
#include <iostream>
using namespace std;
class A
{
public:
virtual void Who(){
cout << "I'm A" << endl;
cout << "*********************************" << endl;
}
};
class B :public A
{
public:
virtual void Who(){
cout << "I'm B" << endl;
cout << "*********************************" << endl;
}
};
void test(A *a)
{
cout << "test *a" << endl;
a->Who();
}
void test(B *b)
{
cout << "test *b" << endl;
b->Who();
}
void test(A a)
{
cout << "test a" << endl;
a.Who();
}
void test(B b)
{
cout << "test b" << endl;
b.Who();
}
int main()
{
B b;
A *a = &b; //等同于:A *a = new B;
a->Who(); //输出 I'm B
b.Who(); //输出 I'm B
test(a); //调用test(A *a),输出 I'm B
test(*a); //调用test(A a),输出 I'm A
test(b); //调用test(B b),输出 I'm B
test(&b); //调用test(B *b),输出 I'm B
}