Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法重载+;运算符添加2个对象_C++_Class_Debugging_Operator Overloading - Fatal编程技术网

C++ 无法重载+;运算符添加2个对象

C++ 无法重载+;运算符添加2个对象,c++,class,debugging,operator-overloading,C++,Class,Debugging,Operator Overloading,我有一个班的员工 #include <iostream> #include <string> using namespace std; class employee { public: double operator + (employee); employee operator + (employee); employee(int); double getSala

我有一个班的员工

#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;
}
#包括
#包括
使用名称空间std;
班级员工
{
公众:
双操作员+(员工);
员工操作员+(员工);
雇员(内部);
双薪();
私人:
双薪;
};
int main()
{  
雇员A(400);
雇员B(800);
库塔拉里;
}
我试图重载+运算符来处理2个employee对象,以便将它们添加到一起,但我遇到了一个编译器错误

职员操作员+(职员)不能超载


我不明白为什么以及如何重载+运算符来添加同一类的两个对象。您有两个运算符
+
,返回类型不同,但参数相同,因此编译器无法判断使用哪一个。因此,在本例中,由于无法“添加”两名员工,我只使用了一名操作员:

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)
{
}

代码的其余部分相同。

不能根据返回类型重载运算符

除此之外,代码中还有一个问题。
你需要重载你不能重载返回类型。