我刚刚开发了一个String类并且重载了=,<<,[]运算符,但是我的运算符+没有工作,请帮助它!
类别:
class String
{
private:
int length;
char *chars;
public:
String oprator+(String &obj);
}
主要代码:
int main ( )
{
String str1;
str1 = "This is first text";
String str2;
str2 = "This is second text";
String bigString = str1 + str2;
bigString = bigString + "This is third text";
}
operator + overload:
String::String operator+ (String &obj)
{
String *temp = new String();
strcpy(temp->chars, chars);
strcat(temp->chars, obj.chars);
return *temp;
}
答案 0 :(得分:1)
您的operator+
应该阅读
class String
{
private:
int length;
char *chars;
String(const char* s, size_t n):
length( n ),
chars( new char[n] )
{
std::copy(s, s+length, chars);
}
public:
explicit String(size_t l):
length(l),
chars( new char[l] )
{
}
String(char const* s):
String(s, strlen(s) )
{
}
String(String const& s):
String(s.chars, s.length)
{
}
String& operator=(String s)
{
std::swap(chars, s.chars);
std::swap(length, s.length);
return *this;
}
~String() {delete[] chars;}
template<size_t N> String(const char s[N]):
String(s, N)
{
}
void append(String const& s)
{
char* tmp = new char[length + s.length];
std::copy(chars, chars+length, tmp);
std::copy(s.chars, s.chars + s.length, tmp + length);
delete[] chars;
chars = tmp;
}
template<typename S> friend S& operator<<(S&, String const&);
};
String operator+(String const& s1, String const& s2)
{
String merged(s1);
merged.append(s2);
return merged;
}
template<typename S> S& operator<<(S& stream, String const& s)
{
return stream << s.chars;
}
int main()
{
String s("bla");
std::cout << s << std::endl;
String s2 = s + "bla";
std::cout << s2 << std::endl;
}
您不想修改参数,因此它应该是const引用。使其成为非const会阻止像
这样的代码bigString = bigString + "This is third text";
因为创建临时String,如果添加非显式构造函数,则无法绑定到l值引用。
运算符不应该是成员函数,而是一个自由函数,可以利用第一个参数的转换。使用免费功能,您可以
bigString = "This is third text" + bigString;
这是成员函数无法实现的,因为char const[]
没有operator+
需要String
。
PS:您可能希望阅读Monoliths "Unstrung"以获取对std :: string接口的批评。