这里我写了2个重载运算符:
stringb operator+(const stringb &a,const stringb &b)
{
stringb temp;
temp.len = a.len + b.len;
temp.p=new char[(temp.len)+1];
strcpy(temp.p, a.p);
strcat(temp.p, b.p);
return (temp);
}
stringb operator-(const stringb &a,const stringb &b)
{
stringb temp;
temp.len=a.len-b.len;
temp.p=new char[temp.len+1];
strcpy(temp.p,a.p);
return (temp);
}
但是,当我编译实际代码时,除了调用这些运算符的部分外,整个代码都有效,而且我得到了垃圾。我的功能有什么问题?
编辑:stringb 类的声明:
class stringb
{
public:
char *p;
int len;
public:
stringb()
{
len=0;
p=0;
}
stringb(const char *s)
{
len=strlen(s);
p=new char[len+1];
strcpy(p,s);
}
stringb(const stringb &s)
{
len=s.len;//strlen(s);
p=new char[len+1];
strcpy(p,s.p);
}
~stringb()
{
delete p;
}
friend int operator==(const stringb &a,const stringb &b);
friend stringb operator+(const stringb &a,const stringb &b);
friend stringb operator-(const stringb &a,const stringb &b);
friend void putstring(const stringb a);
};
最佳答案
你的问题在这里:
~stringb()
{
delete p; // <<<<<
}
如果 temp
超出您的运算符定义的范围,这将被执行。
为了让您的代码正常工作,您需要正确实现 Rule of Three 在您的 stringb
类中。你也可以看看这个不错的 IDE one sample , P0W已根据您的代码进行设置。
关于c++ - 重载运算符函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20164565/