该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
大家帮我分析下下面这段代码,为何会出现指针悬挂现象。
#include
#include
class complex
{
public:
double real;
double imag;
complex(double r=0,double i=0);
~complex() {}
void show();
complex operator ++();
complex operator ++(int);
complex operator --();
complex operator --(int);
complex operator +(complex a);
complex operator -(complex b);
};
class string
{
public:
char *str;
string(char *s);
~string(){ cout<
string &operator =(const string &s);
string operator +(const string &c);
void show();
};
complex::complex(double r,double i)
{
real=r;
imag=i;
}
void complex::show()
{
cout<
}
complex complex::operator ++()
{
this->real++;
this->imag++;
return *this;
}
complex complex::operator ++(int)
{
complex temp(*this);
this->real++;
this->imag++;
return temp;
}
complex complex::operator --()
{
this->real--;
this->imag--;
return *this;
}
complex complex::operator --(int)
{
complex temp(*this);
this->real--;
this->imag--;
return temp;
}
complex complex::operator +(complex a)
{
complex temp;
temp.real=this->real+a.real;
temp.imag=this->imag+a.imag;
return temp;
}
complex complex::operator -(complex b)
{
complex temp;
temp.real=this->real-b.real;
temp.imag=this->imag-b.imag;
return imag;
}
string::string(char *s)
{
str=new char[strlen(s)+1];
strcpy(str,s);
}
string &string::operator=(const string &s)
{
if(this ==&s)
return *this;
delete this->str;
this->str=new char[strlen(s.str)+1];
strcpy(this->str,s.str);
return *this;
}
string string:: operator +(const string &c)//此处造成悬挂
{
string temp("a");
//cout<
delete temp.str;
//cout<
temp.str=new char[strlen(this->str)+strlen(c.str)+2];
//cout<
strcat(temp.str,this->str);
strcat(temp.str," ");
strcat(temp.str,c.str);
cout<
return temp;
}
void string::show()
{
cout<
}
int main()
{
complex a(3.2,4.5);
complex b(1.2,3.2);
complex c;
a.show();
b.show();
cout<
++a;
++b;
a.show();
b.show();
cout<
a++;
b++;
a.show();
b.show();
cout<
c=a+b;
c.show();
cout<
cout<
string str1("hello");
string str2("world");
str1.show();
cout<
str2.show();
cout<
cout<
str1+str2;
//str1=str2;
//str1.show();
cout<
return 0;
}