#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
class Parent
{
protected:
int i;
public:
virtual void f()
{
cout<<"Parent::f()"<<endl;
}
};
class Child: public Parent
{
protected:
int j;
public:
Child(int i, int j)
{
this->i = i;
this->j = j;
}
virtual void f()
{
cout<<"i = "<<i<<" "<<"j = "<<j<<endl;
}
};
int main(int argc, char** argv) {
Parent* p = NULL;
Child* c = NULL;
Child ca[3] = {
Child(1,2),
Child(2,3),
Child(3,4)
};
p = ca;
c = ca;
/*
不要将多态应用于数组
? 指针运算是通过指针的类型进行的
? 多态通过虚函数表实现的
*/
cout<<hex<<&ca[0]<<endl;
cout<<sizeof(Parent)<<endl;
cout<<hex<<&ca[1]<<endl;
cout<<hex<<p+1<<endl;
/*
Parent占8个字节,Child占12个字节,指针运算是按照指针类型来运算的,p+1,即P+8个字节。而ca[0]与ca[1]相距12个字节
0x22feb4
8
0x22fec0
0x22febc
i = 1 j = 2
i = 1 j = 2
i = 2 j = 3
*/
p->f();
c->f();
p++;
c++;
//p->f();
c->f();
return 0;
}
P++ ; 等价于 p = p+1;
p+1; (unsigned int )p + 1*sizeof(*p);
Parent占8个字节,Child占12个字节,指针运算是按照指针类型来运算的,p+1,即P+8个字节。而ca[0]与ca[1]相距12个字节
0x22feb4
80x22fec
00x22febc
i = 1 j = 2
i = 1 j = 2
i = 2 j = 3
所以不要在数组上使用多态!!!!