运算符未编译'+'重载
Overloaded '+' Operator Not Compiling
我试图通过编写一些简单而愚蠢的测试来理解运算符重载的概念。我认为这可能很有用,因为这有助于我更好地理解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;
这不会改变任何一个操作数的值;它保持b
和c
不变,并返回一个完全不同的实例。
,而应重载加法赋值复合运算符 (+=
):
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);
相关文章:
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 错误:使用 clang 没有可行的重载,使用 GCC 编译
- 使用 MINGW gcc 编译时,不会为 std::string 调用重载的新运算符
- 编译以下重载<<需要什么enable_if或其他提示?
- C++编译时检查是否可以用某种类型的参数调用重载函数
- ostream 运算符的编译时重载
- 如何在C++编译时检查运算符的特定重载是否存在
- 简单的 SFINAE 示例以重载函数不编译
- 当其中一个函数未编译时,函数重载查找如何工作?
- 重载运算符编译错误?
- C++ - 在 std::thread 中调用重载函数时编译失败
- 如何重载 const 对象的 [],以便值赋值不会导致编译错误
- 使用 C++11 选项编译 C++98 代码时由于 Boost 标头而导致的不明确重载
- 编译错误:2 个重载没有'this'指针的合法转换。使用结构
- 线性重载:为什么 clang 在 GCC 编译时失败?
- C++运算符新重载、编译错误
- 在编译时推导具有未知类型的函数重载
- 使用 std::enable_if 的模板重载的隐式转换运算符 T() 无法编译
- 重载 == 编译错误 C++
- c++中操作符重载编译错误