其他分享
首页 > 其他分享> > 多重继承下,注意父类指针new子类对象的相关问题

多重继承下,注意父类指针new子类对象的相关问题

作者:互联网

#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; 则报错
image

正常运行结果如下
image

标签:cout,int,子类,base1,报错,new,父类,ptr
来源: https://www.cnblogs.com/appearAndLeave/p/15316734.html