【问题标题】:Overloading custom string operator += in c++在 C++ 中重载自定义字符串运算符 +=
【发布时间】:2014-02-03 06:35:36
【问题描述】:

我正在努力重新创建各种 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);

};

我正在让这些按计划工作,但 += 运算符定义为:

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*)â must have an argument of class or enumerated type string.cpp:28: 错误:âString operator+=(const char*)â must have an argument of class or enumerated type

感谢任何关于我在重载期间做错的信息。

【问题讨论】:

  • += 通常是会员,而不是朋友。 (运算符在您的代码中适用于什么?)

标签: c++ operator-overloading


【解决方案1】:

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&amp;。这些符合Operator overloading 中的指南。

重要更新:

temp_buffer = new char(new_size);

不!您正在分配一个 char 并将其初始化为 new_size,这不是您想要的。将其更改为括号。

temp_buffer = new char[new_size];

现在,您正在正确分配 new_size 数量的 chars 数组。请不要忘记delete[]所有你new[]的人。

【讨论】:

    【解决方案2】:

    += 运算符与 c-strings 一起使用的原因是 std::strings 具有来自 c-strings 的隐式转换构造函数。

    由于您已经有一个转换构造函数,您应该只创建一个带有 String 的 += 运算符。

    【讨论】:

    • 所以对于你的建议,我会将类头设置为 (const String &) 以便我的参数已经是一个字符串?
    • 我相信Mark的解决方案是这里真正的解决方案。至关重要的是,您不要在 operator+= 定义之前包含 String::
    猜你喜欢
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2014-07-06
    • 1970-01-01
    相关资源
    最近更新 更多