#include<iostream>
using namespace std;
class base1
{
public:
int base1_1;
int base1_2;
base1() {
cout << "base1的地址\t" << this << endl;
}
};
class base2 {
public :
int base2_1;
int base2_2;
base2() {
cout << "base2的地址\t" << this << endl;
}
};
class son :public base1, public base2 {
public :
son() {
cout << "son 的地址\t" << this << endl;
}
int son_1;
int son_2;
};
int main() {
cout << "sizeof base1\t" << sizeof(base1) << endl;
cout << "sizeof base2\t" << sizeof(base2) << endl;
cout << "sizeof son\t" << sizeof(son) << endl;
base2 * base2_ptr = new son(); //实际分配24字节,
long *long_ptr = (long *)( base2_ptr);
cout << "base2_ptr 的地址 \t" << long_ptr<<"\tbase2_ptr:\t"<<base2_ptr<< endl;
//delete base2_ptr; //报错,原因:base2_ptr 返回的地址不是分配的首地址,是this 指调整后的地址
son * son_ptr = (son *)base2_ptr;
cout << "son_ptr的地址:\t" << son_ptr << endl; //这是new son()实际分配的首地址
delete son_ptr; //正常的
return 0;
}
若是 delete base2_ptr;
则报错
正常运行结果如下