我希望重载,比方说,加法运算符,让它添加同一类的两个对象。当我在头文件的类声明中声明这个“operator+”原型(prototype)函数时,我将这两个对象作为参数传入。我收到一个编译器错误,提示“二进制‘operator +’的参数太多”。我在网上搜索答案,发现在编译出的头文件中的类声明之外声明一个内联函数。我想知道我做错了什么,或者我是否在这里遗漏了什么。这是我在头文件中使用的代码。
class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
Person operator+(Person r, Person i);
};
编译时出现我上面提到的错误。下面是可以正常编译的代码。
class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
};
inline Person operator+(Person r, Person i)
{
return Person(0,0);
}
最佳答案
如果您将 oparator+
声明为实例函数,那么第一个参数将作为 this
对象传递,因此您只需要再增加一个参数。阅读本文以获取更多信息,尤其是尝试理解 const
概念:
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
引用文章中建议的最佳方法是:
class Person
{
...
Person &operator+=(const Person &i);
const Person operator+(const Person &i) const;
...
};
Person &Person::operator+=(const Person &i) {
... // Do the compound assignment work.
return *this;
}
const Person Person::operator+(const Person &i) const {
Person result = *this; // Make a copy of myself. Same as MyClass result(*this);
result += i; // Use += to add other to the copy.
return result; // All done!
}
如果您决定使用 const
版本,请记住您只能在 this
和 i< 上调用
引用。这是首选方式。const
方法
我引用的文章更详细地解释了重载 +=
然后使用 +=
定义 +
的想法。这是个好主意,因为必须单独重载 +=
运算符。
此外 - David Rodríguez 建议将 operator+
作为一个自由函数来实现,而不管 += 是否存在。
关于C++:重载数学运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3078469/