基类指针指向派生类对象的局限性

有虚继承,不建议基类指针指向派生类对象

#include<iostream>
using namespace std;

class Base
{
public:
	Base(int a) :ma(a)
	{
		cout << "Base::Base(int)" << endl;
	}
protected:
	int ma;
};
class Derive :virtual public Base
{
public:
	Derive(int b) :mb(b), Base(b){}
private:
	int mb;
};
int main()
{
	Base* pbase = new Derive(10);
	delete pbase;
}

以上程序崩溃,分析崩溃原因???

注意在此加入虚析构已经不能解决此处发生的错误了。

修改:

int main()
{
	Base* pbase = new Derive(10);
	delete (Base*)((char*)pbase - 8);
	return 0;
}

此时只能通过对指针进行减操作才更改程序

猜你喜欢

转载自blog.csdn.net/Aspiration_1314/article/details/86557939