我正在努力重新创建各种 C++ 类型,以便更好地理解它们的工作原理。我目前陷入了 += 运算符的困境,无法找到我的声明的问题所在。这是我的类(class)的代码:
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);
};
我正在让这些按计划工作,但 += 运算符定义为:
String operator+=(const char * p){
int p_size = std::char_traits<char>::length(p);
int new_size = size+p_size;
char * temp_buffer;
temp_buffer = new char(new_size);
for(int i=0; i<size; i++){
temp_buffer[i] = buffer[i];
}
for(int i=size, j=0; j<p_size;i++,j++){
temp_buffer[i] = p[j];
}
delete buffer;
buffer = new char[new_size];
size = new_size;
for(int i=0; i<size; i++){
buffer[i] = temp_buffer[i];
}
return *this;
}
我的错误是 string.h:29: 错误:“String operator+=(const char*)”必须具有类或枚举类型的参数 string.cpp:28: 错误:“String operator+=(const char*)”必须具有类或枚举类型的参数
任何有关我在重载期间做错的事情的信息都会受到赞赏。
最佳答案
operator+=
是一个二元运算符,因此需要两个操作数(例如 myString += "str",
,其中 myString
和 “str”
是操作数)。
但是,您有一个格式不正确的operator+=
,因为它只接受一个参数。请注意,您的 operator+=
是一个独立函数(不是类方法),它返回一个 String
并接受单个 const char*
论证。
要解决您的问题,请将您的 operator+=
设为成员函数/方法,因为到那时,您将拥有一个隐式 this
参数,该参数将用作左侧操作数。
class String {
...
String& operator+=(const char * p);
};
及其定义
String& String::operator+=(const char * p) {
...
return *this;
}
请注意,您现在返回对 *this
的引用,并且其返回类型更改为 String&
。这些均符合 Operator overloading 中的指南。 .
重要更新:
temp_buffer = new char(new_size);
不!您正在分配一个 char
并将其初始化为 new_size
,但这不是您想要的。将其更改为括号。
temp_buffer = new char[new_size];
现在,您正在正确分配 new_size
个 char
的数组。并且请不要忘记删除[]
所有您new[]
的内容。
关于c++ - 在 C++ 中重载自定义字符串运算符 +=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21521116/