C++重载+连接字符串
来源:百度知道 编辑:UC知道 时间:2024/06/19 23:43:12
自己写了个小程序,VC检查没问题,但是实施的时候却不能运行,估计是重载+的时候出错了,希望高手解救,万分感谢!
#include<iostream.h>
#include<string.h>
class Str
{public:
Str(){};
Str(char*pt);
Str(const Str&);
Str operator +(Str);
void show();
private:
char*p;
};
Str::Str(char*pt){p=new char[strlen(pt)+1];
if(p!=0)strcpy(p,pt);
}
Str::Str(const Str& obj)
{
p=new char[strlen(obj.p)+1];
if(p!=0)strcpy(p,obj.p);
}
void Str::show()
{cout<<p;
}
Str Str::operator +( const Str t)
{
Str temp;
strcpy(temp.p ,t.p );
strcat(temp.p ,p);
return temp;
}
void main()
{ Str obj_a("I");
Str obj_b("am");
Str obj_c;
obj_c=obj_a+obj_b;
}
#include<iostream.h>
#include<string.h>
class Str
{public:
Str(){};
Str(char*pt);
Str(const Str&);
Str operator +(Str);
void show();
private:
char*p;
};
Str::Str(char*pt){p=new char[strlen(pt)+1];
if(p!=0)strcpy(p,pt);
}
Str::Str(const Str& obj)
{
p=new char[strlen(obj.p)+1];
if(p!=0)strcpy(p,obj.p);
}
void Str::show()
{cout<<p;
}
Str Str::operator +( const Str t)
{
Str temp;
strcpy(temp.p ,t.p );
strcat(temp.p ,p);
return temp;
}
void main()
{ Str obj_a("I");
Str obj_b("am");
Str obj_c;
obj_c=obj_a+obj_b;
}
问题处在这个函数里:
Str Str::operator +( const Str t)
{
Str temp;
strcpy(temp.p ,t.p );
strcat(temp.p ,p);
return temp;
}
temp对象的成员变量 p 指向的是一个未知的地址,所以strcpy(temp.p, t.p)是出错。建议改成下面这样:
Str temp(t.p);
strcat(temp.p, p);
return temp;
我这里没有vc环境,没有调试,
默认构造函数,改成
Str()
{
p=0;
};
还有就是楼上说的,指针变量未初始化,形成野指针。
你加上include<cstring>试试,因为你使用了 c 串的函数