一个简单小程序运行出错,好像是delete d处发生了问题,不明白为什么,麻烦大佬们瞅一瞅
#include<iostream>
using namespace std;
#include<string>
//抽象类
class CPU
{
public:
virtual void calculate() = 0;
};
class Display
{
public:
virtual void disp() = 0;
};
//子类继承并重写抽象方法
class Inter :public CPU, public Display
{
public:
void calculate()
{
cout << "Inter牌CPU正在计算" << endl;
}
void disp()
{
cout << "Inter牌显卡正在工作" << endl;
}
};
class Lenovo :public CPU, public Display
{
public:
void calculate()
{
cout << "Lenovo牌CPU正在计算" << endl;
}
void disp()
{
cout << "Lenovo牌显卡正在工作" << endl;
}
};
class computer
{
public:
void show(CPU* c, Display* d)
{
c->calculate();
d->disp();
if (c != NULL)//这里都可以释放内存
{
delete c;
c = NULL;
}
if (d != NULL)//这里判断了d不为空指针
{
delete d;//好像是这里程序崩了,为啥不能释放啊????
d = NULL;
}
}
};
int main()
{
computer c;
c.show(new Lenovo, new Inter);
}
谢谢大家!!!
这是因为你的函数void show(CPU* c, Display* d);而不是void show(Lenovo* c, Inter* d);
无虚析构函数的时候系统会认为你释放的是CPU对象内存而不是Lenovo对象,无法正确释放内存
有虚析构函数的存在,在释放内存时虚表中的信息找到实际对象(Lenovo)所在的内存块进行释放
给两个接口加上虚析构函数
class CPU
{
public:
virtual ~CPU() {}
virtual void calculate() = 0;
};
class Display
{
public:
virtual ~Display() {}
virtual void disp() = 0;
};