c++ - 无法重载 + 运算符来添加 2 个对象

标签 c++ class debugging operator-overloading

我有一名类(class)员工

#include <iostream>
#include <string>
using namespace std;

class employee
{
    public:

            double operator + (employee);
            employee operator + (employee);
            employee(int);
            double getSalary();

    private:

           double salary;

};

int main()
{  
  employee A(400);
  employee B(800);

  cout<<A+B;

  employee C = A+B; //overload + operator to add 2 object together

  cout<<C.getSalary();

}

employee::employee(int salary)
{
    this->salary = salary;
}


double employee::operator + (employee e)
{
    double total;

    total = e.salary + this->salary;

    return total;    
}

employee employee::operator + (employee e)
{

    double total;

    total= this->salary + e.salary;

    employee c(total);

    return c;


}

double employee::getSalary()
{
    return this->salary;
}

我正在尝试重载 + 运算符以处理 2 个员工对象,以便我可以将它们添加在一起,但出现编译器错误

employee operator + (employee) cannot be overloaded;

我不明白为什么以及如何重载 + 运算符来添加同一类的 2 个对象

最佳答案

您有两个运算符 +,其返回类型不同但参数相同,因此编译器无法判断使用哪一个。因此,对于此示例,由于您无法“添加”两名员工,所以我只使用了一名运算符:

class employee
{
    public:
            //you only need one + operator
            double operator + (const employee & e)const;
            //constructor is taking a double so that your code works.
            employee(double);
    private:
           double salary;
};

double operator + (const employee & e)const
{
    return salary + e.salaty;    
}
employee::employee(double s)
    :salary(s)
{
}

其余代码相同。

关于c++ - 无法重载 + 运算符来添加 2 个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20212754/

相关文章:

c++ - QWaitCondition : Destroyed while threads are still waiting

c++ - 如何在 Visual Studio Code 中为 C++ 启用 IntelliSense?

java - 静态类是否只包含java中的静态方法?

c++ - 有没有办法在opencv c++中检查矩阵中的数据

ios - 调试 'CALayer position contains NaN: [nan nan]'

c++ - 使用代码 :Blocks on Linux 的 C++ 函数中的 "Not Declared in scope"

c++ - Arduino C++ : Does the F() macro make any sense inside a function?

class - 没有合适的默认构造函数可用?

java - 单独的相机类别还是合并在一起?

php - 用于 Web 开发的 Windows 兼容 IDE?