对多态的理解:
#include<iostream>
using namespace std;
class A
{
public:
virtual void printA()
{
cout << "A" << endl;
}
virtual void printB()
{
cout << "B" << endl;
}
void printSomething() // 此方法就是个接口,有所定义(定义了输出顺序),后代可根据需要进行重写。
{
printA();
printB();
}
};
class B:public A
{
public:
virtual void printA()
{
cout << "AA" << endl;
}
virtual void printB()
{
cout << "BB" << endl;
}
};
void main()
{
A *pA = new B ;//也可以B *pA = new B ;这样对于结果肯定是无疑问的。但是用A类型接收实例化B对象
pA->printSomething(); // 因为对于B对象中是没有printSomething(),A对象中有此方法。则调用其基类的此方法,但是,对象B中重写了printSomething()内的方法,调用的还是对象B中的printA()和printB()
}
输出结果为 AA(回车)BB