运算符未编译'+'重载

Overloaded '+' Operator Not Compiling

本文关键字:重载 编译 运算符      更新时间:2023-10-16

我试图通过编写一些简单而愚蠢的测试来理解运算符重载的概念。我认为这可能很有用,因为这有助于我更好地理解C++。

为什么此示例实现Animal类和std::string的串联运算符不编译?G ++给了我以下错误:

额外资格"动物::"在成员"操作员+"[-允许]

这是代码:

#include <iostream>
using namespace std;
class Animal {
public:
    string _type;
    string _name;
    string _sound;

    Animal & Animal::operator+(const string & o);
};

Animal & Animal::operator+(const string & o) {
    cout << "plus operator n";
    this->_name=o;
    return *this;
}

int main( int argc, char ** argv ) {
    Animal a;
    a+"hhh";
    cout<<a._name;
    return 0;
}
Animal & Animal::operator+(const string & o);

无效。它应该是:

Animal & operator+(const string & o);

此外,简单加法运算符的实现会导致修改其中一个操作数。对于加法运算符来说,这从来都不是一件好事。

例如:

int a, b = 5, c = 3;
a = b + c;

这不会改变任何一个操作数的值;它保持bc不变,并返回一个完全不同的实例。

因此,不应重载加法运算符

,而应重载加法赋值复合运算符 (+=):

Animal & operator+=(const string & o);

当然,更改实现并相应地调用它:

Animal & Animal::operator+=(const string & o) {
    cout << "plus operator n";
    this->_name=o;
    return *this;
}

和:

a += "hhh";

类中的operator+声明不需要限定,正是因为它是在类中声明的:

class Animal {
  // ...
  Animal& operator+(const string& o);
}

定义函数时,此限定是必需的,因为您在类外部定义它 - 编译器需要知道函数属于哪个类。

原型中不需要Animal::,因为它已经在Animal类中了。只需使用:

Animal & operator+(const string & o);

Animal::限定应该在成员函数的定义中使用,而不是在声明中使用。因此,将运算符声明更改为:

Animal & operator+(const string & o);