C++:重载数学运算符

标签 c++ operator-overloading

我希望重载,比方说,加法运算符,让它添加同一类的两个对象。当我在头文件的类声明中声明这个“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 版本,请记住您只能在 thisi< 上调用 const 方法引用。这是首选方式。

我引用的文章更详细地解释了重载 += 然后使用 += 定义 + 的想法。这是个好主意,因为必须单独重载 += 运算符。

此外 - David Rodríguez 建议将 operator+ 作为一个自由函数来实现,而不管 += 是否存在。

关于C++:重载数学运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3078469/

相关文章:

c++ - 在任意数据类型上使用 <algorithm> 库

c++ - 无法在eclipse中链接Opencv静态库(已添加-ldl!)

c++ - 这些行号在此错误中意味着什么?

c++ - 如何使用 OpenCV 或其他图像处理库从 RGB 数据写入 YUV 420 视频帧?

c++ - 类和运算符

c++ - CUDA 矩阵类的 operator() 重载

c++ - 操作重载返回值(或类似的东西)

excel - Excel VBA 中的运算符重载

c++ - AfxMessageBox - 访问冲突

c++ - 访问者和模板化虚拟方法