class Parent{
public:
Parent(){}
Parent(int a){
m_a = a;
}
virtual void print(){
cout << "Parent a: " << m_a << endl;
}
int m_a;
private:
};
class Child :public Parent{
public:
Child(int c){
//m_c = c;
}
Child(int a, int c) :Parent(a) {
//this->m_c = c;
}
void print(){
cout << "Child a: " << m_a << " m_c: " << endl;
}
private:
int m_c;
};
Main:
Parent* pP = NULL;
Child* pC = NULL;
Child array[] = { Child(1), Child(2), Child(3), Child(4) };
cout << "sizeof(parent): " << sizeof(Parent) << endl;//8
cout << "sizeof(Child): " << sizeof(Child) << endl;//12
pP = array;
pC = array;
pP->print();
pC->print();//发生多态
pP++;
pC++;
pP->print();//步长不一致出错 父类指针步长为8 子类指针步长为12 指针++出错
pC->print();
多态 父类指针与子类指针的步长不一致
最新推荐文章于 2023-11-01 21:45:00 发布