我有这个问题,在我试图重载为我的自定义字符串类的附加功能,所以我做一个临时对象到两个物体的长度和数组的加在一起,但我不断收到分段错误我不知道为什么。我测试了我的作业操作员作品和我的平等操作员,他们都完美地工作。String类+运营商
myString myString::operator+(const myString& str) const{
int p = 0;
myString tmp;
tmp.sLength = sLength + str.sLength;
tmp.s = new char[tmp.sLength];
while (p != (sLength - 1))
{
tmp.s[p] = s[p];
p++;
}
while (p != (tmp.sLength - 1))
{
tmp.s[p] = str.s[(p - sLength)];
p++;
}
return tmp;
//tmp.s = NULL;
}
myString& myString::operator=(const myString& str)
{
if (this != &str)
{
if (s != NULL)
{
if (str.s == NULL)
{
sLength = 0;
s = NULL;
}
else
{
delete [] s;
s = new char [str.sLength];
sLength = str.sLength;
for (int i = 0; i < sLength; i++)
s[i] = str.s[i];
}
}
}
return *this;
}
请发布[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。你的代码是否符合[The Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree)? – MikeCAT
您需要尝试gdb:在gdb中运行代码('run'),当它发生故障时,爬上堆栈以识别代码(使用'up')。看看这个代码。尝试“p * this”,看你的对象的状态,或“p localVar” –