编译通过,运行错误!大家看看是什么原因。
代码:
//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;
}