C++ 超载'+';运算符未编译
我试图通过编写一些简单、愚蠢的测试来理解操作符重载的概念。我认为这可能是有用的,因为这有助于我更好地理解C++。p> 为什么这个示例没有编译实现C++ 超载'+';运算符未编译,c++,C++,我试图通过编写一些简单、愚蠢的测试来理解操作符重载的概念。我认为这可能是有用的,因为这有助于我更好地理解C++。p> 为什么这个示例没有编译实现Animal类和std::string的连接运算符?G++给了我以下错误: 额外资格“动物::”成员“操作员+”[-F允许] 代码如下: #include <iostream> using namespace std; class Animal { public: string _type; string _name;
Animal
类和std::string
的连接运算符?G++给了我以下错误:
额外资格“动物::”成员“操作员+”[-F允许]
代码如下:
#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;
}
#包括
使用名称空间std;
类动物{
公众:
字符串类型;
字符串\u名称;
弦乐;
动物和动物::运算符+(常量字符串和o);
};
动物和动物::运算符+(常量字符串和o){
cout_name=o;
归还*这个;
}
int main(int argc,字符**argv){
动物a;
a+“hh”;
库特
无效。它应该是:
Animal & operator+(const string & o);
此外,简单加法运算符的实现会修改其中一个操作数。这对于加法运算符来说是件好事
例如:
int a, b = 5, c = 3;
a = b + c;
这不会改变两个操作数的值;它保持b
和c
不变,并返回一个完全不同的实例
因此,不应重载加法运算符,而应重载加法赋值复合运算符(+=
):
当然,要改变实施方式,并相应地要求:
Animal & Animal::operator+=(const string & o) {
cout << "plus operator \n";
this->_name=o;
return *this;
}
原型中不需要Animal::
,因为它已经在Animal
类中了。只需使用:
Animal & operator+(const string & o);
类中的operator+
声明不需要限定,因为它是在类中声明的:
class Animal {
// ...
Animal& operator+(const string& o);
}
定义函数时,此限定是必需的,因为您在类之外定义了函数-编译器需要知道函数属于哪个类。动物:
限定应在成员函数的定义中使用,而不是在声明中使用。因此,将运算符声明更改为:
Animal & operator+(const string & o);
此运算符应称为
+=
或
Animal & operator+(const string & o);
class Animal {
// ...
Animal& operator+(const string& o);
}
Animal & operator+(const string & o);