首页 > 解决方案 > 返回类型重载运算符

问题描述

我有一个问题,可能是微不足道的... 运算符重载对返回类型有限制吗?我试图重载运算符 +,在参数中我有两个 Nodo 类的对象,我想返回属性的总和(使用 get 方法),它们是 int。所以我写了一个外部函数int operator+(Nodo a,Nodo b),但这没有用……所以我尝试了int operator+(int tot,Nod a),这有效。我想返回类型必须是参数之一?

class Nodo
{
    private:
        Nodo *Next;
        Employee *Emp;

    public:
        Nodo(){}
        Nodo(Nodo *a,Employee *b):Next(a),Emp(b){}
        virtual ~Nodo(){}
        void SetNext(Nodo *a){Next=a;};
        Nodo* GetNext(){return Next;}
        void SetEmployee(Employee *emp){Emp=emp;}
        Employee* GetEmployee(){return Emp;}
};

class Employee
{
    private:
        string name;
        int salary;

    public:
        Employee(string name,int salary):name(name),salary(salary){}
        virtual ~Employee() {}
        string GetName(){return name;}
        int GetSalary(){return salary;}
        virtual void PrintInfo(){cout<<"Nome "<<name<<" Salario "<<salary<<endl;}
};

我试过了

int operator+(Nodo a,Nodo b)
{
  int totale;
  totale=a.GetEmployee()->GetSalary()+b.GetEmployee()->GetSalary();
  return totale;
}

结果就是崩溃。

虽然这项工作。

int operator+(int tot,Nodo a)
{
  int totale;
  totale=tot+a.GetEmployee()->GetSalary();
  return totale;
}

标签: c++operator-overloadingreturn-type

解决方案


运算符重载有关于它们可以采用的参数的类型数量的规则。
例如:

  1. +声明为成员函数的二元运算符(例如)采用一个参数;如果声明为全局函数,它们有两个参数。

  2. 重载的运算符不能有默认参数。

  3. 成员函数重载运算符的第一个参数始终是调用运算符的对象的类类型(声明运算符的类,或从该类派生的类)。没有为第一个参数提供转换。

但是没有关于返回类型的规则。因此,您可以从重载运算符返回任何类型。


推荐阅读