-2

我必须为下面的字符串运算符做一个实现

String operator +=(const String &str); // this is my declaration which is in my header file

目标是返回一个通过将传递的字符串附加到调用该方法的字符串而形成的字符串。

到目前为止,这是我的代码/实现,但它有错误,我被卡住了。

String::String::operator +=(const String &str)
{
   strcat(contents, str.contents);
   len += str.len;
}

我怎样才能解决这个问题?两个错误是第一个'String'和'operator'

这是运算符的错误:声明与“String String::operator+=(const String &str)”不兼容

和一个字符串;缺少显式类型(假定为“int”)

4

2 回答 2

3

这是你的问题:

String::String::operator +=(const String &str)
      ^^

两个标记的字符应该被一个空格替换,这样你就有了一个返回类型:

String String::operator +=(const String &str)
{
    //...
}
于 2013-07-09T01:50:49.530 回答
1

您正在修改String调用操作员的 。它是一个复合运算符(+=运算符的混合),因此您需要返回对String已修改的 的引用:

String& operator +=(const String &str); 

String& String::operator +=(const String &str)
{
    strcat(contents, str.contents);
    len += str.len;
    return *this;
}
于 2013-07-09T03:02:11.560 回答