2016-11-19 77 views
-1

我有这个问题,在我试图重载为我的自定义字符串类的附加功能,所以我做一个临时对象到两个物体的长度和数组的加在一起,但我不断收到分段错误我不知道为什么。我测试了我的作业操作员作品和我的平等操作员,他们都完美地工作。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; 
} 
+2

请发布[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。你的代码是否符合[The Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree)? – MikeCAT

+1

您需要尝试gdb:在gdb中运行代码('run'),当它发生故障时,爬上堆栈以识别代码(使用'up')。看看这个代码。尝试“p * this”,看你的对象的状态,或“p localVar” –

回答

1

当此循环

while (p != (sLength - 1)) 
{ 
    tmp.s[p] = s[p]; 

    p++; 
} 

结束其迭代变量p将等于sLength -1

因此,在这个循环中

while (p != (tmp.sLength - 1)) 
{ 
    tmp.s[p] = str.s[(p - sLength)]; 

    p++;  
} 

在第一次迭代你有

tmp.s[sLength -1] = str.s[(sLength -1 - sLength)]; 

tmp.s[sLength -1] = str.s[(-1)]; 
           ^^^^ 

而且目前尚不清楚为什么循环使用这样的p != sLength - 1条件。为什么他们不使用p != sLength这样的条件?

复制赋值运算符也是错误的。

例如,如果s!= NULL你只是分配给它NULL,而不删除先前分配的内存。

if (s != NULL) 
{ 
    if (str.s == NULL) 
    { 
     sLength = 0; 
     s = NULL; 
     ^^^^^^^^ 

而且如果s等于NULL,然后分配给它虽然没有什么可以str.s是一个非空指针。

另外一个问题是,为什么你在循环

 for (int i = 0; i < sLength; i++) 
         ^^^^^^^^^^^ 
     s[i] = str.s[i]; 

代替

 for (int i = 0; i < sLength - 1; i++) 
         ^^^^^^^^^^^^^^^ 
     s[i] = str.s[i]; 

,因为它是在operator +这里使用以下条件?

+0

感谢您的帮助 – yasky

+0

@yasky根本没有。不用谢。:) –