重载'+'运算符未编译

时间:2013-02-02 15:58:06

标签: c++

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

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

  

成员'运营商+'[-fpermissive]

上的额外资格'Animal ::'

这是代码:

#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;
}

4 个答案:

答案 0 :(得分:4)

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";

答案 1 :(得分:2)

你班级中operator+的声明不需要被限定,正是因为它是在班级中宣布的:

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

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

答案 2 :(得分:0)

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

Animal & operator+(const string & o);

答案 3 :(得分:0)

Animal::限定条件应在成员函数的定义中使用,而不是在声明中使用。因此,将您的运营商声明更改为:

Animal & operator+(const string & o);
相关问题