重载自定义字符串运算符+;=在c++; 我正在努力重建各种C++类型,以便更好地理解它们的工作方式。我目前一直使用+=运算符,找不到我的声明有什么问题。以下是我的课程代码: class String { int size; char * buffer; public: String(); String(const String &); String(const char *); int length(){return size;}; friend bool operator==(const String &, const String &); friend bool operator<=(const String &, const String &); friend bool operator<(const String &, const String &); friend ostream & operator<<(ostream &, const String &); char operator[](const int); // friend String operator+=(const String &,const char * p); friend String operator+=(const char * p); }; 类字符串{ 整数大小; 字符*缓冲区; 公众: 字符串(); 字符串(常量字符串&); 字符串(常量字符*); int length(){return size;}; 友元布尔运算符==(常量字符串&,常量字符串&); friend bool运算符+=运算符使用c字符串的原因是,std::strings具有c字符串的隐式转换构造函数

重载自定义字符串运算符+;=在c++; 我正在努力重建各种C++类型,以便更好地理解它们的工作方式。我目前一直使用+=运算符,找不到我的声明有什么问题。以下是我的课程代码: class String { int size; char * buffer; public: String(); String(const String &); String(const char *); int length(){return size;}; friend bool operator==(const String &, const String &); friend bool operator<=(const String &, const String &); friend bool operator<(const String &, const String &); friend ostream & operator<<(ostream &, const String &); char operator[](const int); // friend String operator+=(const String &,const char * p); friend String operator+=(const char * p); }; 类字符串{ 整数大小; 字符*缓冲区; 公众: 字符串(); 字符串(常量字符串&); 字符串(常量字符*); int length(){return size;}; 友元布尔运算符==(常量字符串&,常量字符串&); friend bool运算符+=运算符使用c字符串的原因是,std::strings具有c字符串的隐式转换构造函数,c++,operator-overloading,C++,Operator Overloading,既然您已经有了一个转换构造函数,那么您应该只创建一个+=运算符,该运算符接受一个字符串运算符+=是一个二进制运算符,因此需要两个操作数(例如myString+=“str”、,其中myString和“str”是操作数) 但是,您的运算符+=格式不正确,因为它只接受一个参数。请注意,运算符+=是一个独立函数(不是类方法),它返回一个字符串并接受一个常量字符*参数 要解决您的问题,请将运算符+=设置为成员函数/方法,因为到那时,您将拥有一个隐式this参数,该参数将用作左侧操作数 class Stri

既然您已经有了一个转换构造函数,那么您应该只创建一个+=运算符,该运算符接受一个
字符串
运算符+=
是一个二进制运算符,因此需要两个操作数(例如
myString+=“str”、
,其中
myString
“str”
是操作数)

但是,您的
运算符+=
格式不正确,因为它只接受一个参数。请注意,
运算符+=
是一个独立函数(不是类方法),它返回一个
字符串
并接受一个
常量字符*
参数

要解决您的问题,请将
运算符+=
设置为成员函数/方法,因为到那时,您将拥有一个隐式
this
参数,该参数将用作左侧操作数

class String {
    ...
    String& operator+=(const char * p);
};
及其定义

String& String::operator+=(const char * p) {
   ...
   return *this;
}
请注意,您现在返回对
*this
的引用,其返回类型更改为
字符串&
。这些都符合中的指导原则

关键更新:

不!您正在分配单个
字符
,并将其初始化为
新大小
,这不是您想要的。请将其更改为括号

temp_buffer = new char[new_size];

现在,您正在正确地分配一个
new\u size
数组
char
s的数量。请不要忘记
delete[]
所有您
new[]

+=
的人通常是成员,而不是朋友。(操作符会在您的代码中应用什么?)(const String&)那么我的参数已经是字符串了吗?我相信Mark的解决方案才是真正的解决方案。关键是不要在运算符+=定义之前包含
String::
temp_buffer = new char(new_size);
temp_buffer = new char[new_size];