我有這個問題,在我試圖重載爲我的自定義字符串類的附加功能,所以我做一個臨時對象到兩個物體的長度和數組的加在一起,但我不斷收到分段錯誤我不知道爲什麼。我測試了我的作業操作員作品和我的平等操作員,他們都完美地工作。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」 –