我有一名班级员工
#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个员工对象,因此我可以将它们一起添加但我收到编译器错误
员工操作员+(员工)不能超载;
我不明白为什么以及如何重载+运算符以添加同一类的2个对象
答案 0 :(得分: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)
{
}
其余代码是相同的。
答案 1 :(得分:0)
你不能在返回类型的基础上重载运算符..
除此之外,您的代码还有一个问题。 你需要重载&lt;&lt;运算符采用'employee'类型的右手操作数