64,266
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class a{
public:
a():c(new int[10]){}
~a(){delete []c;}
protected:
int *c;
};
class b:public a{
public:
b():d(new int [100]){}
~b(){delete []c;delete []d;}//就是这,应不应该delete []c;
//能说个理由更好。因为delete []c;写不写程序都能过。
private:
int *d;
};
int main()
{
a y;
b z;
return 0;
}
//或者这么写
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class a
{
public:
a():c(new int[10])
{
}
~a()
{
//delete []c;//这里不释放
}
protected:
int *c;
};
class b:public a
{
public:
b():d(new int [100])
{
}
~b()
{
delete []c;//这里可以这么写,释放基类没释放的内存空间
delete []d;
}
private:
int *d;
};
int main()
{
a y;
b z;
return 0;
}
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class a
{
public:
a():c(new int[10])
{
}
~a()
{
delete []c;
}
protected:
int *c;
};
class b:public a
{
public:
b():d(new int [100])
{
}
~b()
{
delete []c;//这里不应该写,因为c被释放了2次,会报错
delete []d;
}
private:
int *d;
};
int main()
{
a y;
b z;
return 0;
}
virtual ~a(){delete []c;//少了个virtual