文章目录
基类指针指向派生类对象,基类指针的首地址永远指向子类从基类继承的基类起始地址。
代码
cpp
#include <iostream>
using namespace std;
class base
{
public:
void show() { cout << "base:: show"; }
};
class derive:public base
{
public:
virtual void show() { cout << "derive:: show"; }
};
int main()
{
base* p = new derive;
p->show();
delete p;
}
以上代码在调用delete 的时候出错,因为在调用deletes时传入的地址和我么预想的不一样,才会导致软件崩溃
代码2
cpp
#include <iostream>
using namespace std;
class base
{
public:
void show() { cout << "base:: show"<<endl; }
void operator delete(void *p)
{
cout << "operator delete p" <<p<< endl;
free(p);
}
};
class derive:public base
{
public:
virtual void show() { cout << "derive:: show"; }
void* operator new (size_t size)
{
void* p = malloc(size);
cout << "operator new " << p << endl;
return p;
}
};
int main()
{
base* p = new derive;
p->show();
delete p;
}
综上,子类带虚函数,而基类不带虚函数是一件非常危险的操作,编译器对指针的指向超出我们的预期,往往导致很难排查的问题