编译通过,运行错误!大家看看是什么原因。

bobshi 2003-04-18 05:08:29
代码:
//dynamicint.h
#ifndef DYNAMICINT_CLASS
#define DYNAMCIINT_CLASS

class DynamicInt
{
public:
DynamicInt(int n=0);
DynamicInt(const DynamicInt& x);

~DynamicInt();

DynamicInt& operator = (const DynamicInt& x);

int GetVal();
void SetVal(int n);

//friend ostream& operator << (ostream& ostr, const DynamicInt& x);
//friend istream& operator >> (istream& istr, const DynamicInt& x);
private:
int *pn;

};

DynamicInt::DynamicInt(int n)
{
pn=new int(n);
}

DynamicInt::DynamicInt(const DynamicInt& x)
{
pn=new int(*x.pn);
}

DynamicInt::~DynamicInt()
{
delete pn;
}

DynamicInt& DynamicInt::operator = (const DynamicInt& x)
{
*pn=*x.pn;

return *this;
}

int DynamicInt::GetVal()
{
return *pn;
}

void DynamicInt::SetVal(int n)
{
delete pn;
*pn=n;
}

/*ostream& operator << (ostream& ostr,const DynamicInt& x)
{
ostr << *(x.pn) << endl;
return ostr;
}

istream& operator >> (istream& istr, const DynamicInt& x)
{
istr >> *(x.pn);
return istr;
}*/
#endif

//test.cpp

#include <iostream>
#include "dynamicint.h"
using namespace std;

int main()
{
DynamicInt D(6);
cout << D.GetVal() << endl;

DynamicInt *p;
p=new DynamicInt(50);
cout << (*p).GetVal() << endl;
delete p;

DynamicInt *a;
a=new DynamicInt[10];
if (a == NULL)
{
cerr << "allocation memory failty!" << endl;
}
for (int i = 0; i < 10; i++)
{
a[i].SetVal(100);
}

for (int j =0; j < 10; j++)
{
cout << a[j].GetVal() <<",";
}
cout << endl;
delete [] a;

return 0;
}
...全文
30 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
point_to 2003-04-18
  • 打赏
  • 举报
回复
你这里不能在SetVal里先delete再赋值,如果是的话,赋到内存哪里了呢?通俗吧???
而且在你的析构函数里,又delete了一块已经不存在的内存了!






delete pn;
pn=new int;
*pn=n;


*pn=n;
在这里没什么区别,只是第一种显得冗余,而且代码多了点,也占用了多点的资源,而且两种方法里,类的成员pn指向的是不一样的内存处,这个没什么难得哦,如果是copy assignment operator那就不一样了,具体可以看书!
bobshi 2003-04-18
  • 打赏
  • 举报
回复
to:这里我有点不明白,为什么有时要不new 分配内存,而有时不用呢?

void DynamicInt::SetVal(int n)
{
// delete pn;DynamicInt::~DynamicInt()里的delete pn;有了错误勒!!!
// 或者不要或者

// delete pn;
// pn=new int;
// *pn=n;
*pn=n;
}

这两种方法有什么区别吗?
point_to 2003-04-18
  • 打赏
  • 举报
回复

void DynamicInt::SetVal(int n)
{
// delete pn;DynamicInt::~DynamicInt()里的delete pn;有了错误勒!!!
// 或者不要或者

// delete pn;
// pn=new int;
// *pn=n;
*pn=n;
}

DynamicInt::~DynamicInt()
{
delete pn;
}
diabloqin 2003-04-18
  • 打赏
  • 举报
回复
什么错误,贴出来看看

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧