c++ - 返回类型重载运算符
问题描述
我有一个问题,可能是微不足道的... 运算符重载对返回类型有限制吗?我试图重载运算符 +,在参数中我有两个 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;
}
解决方案
运算符重载有关于它们可以采用的参数的类型和数量的规则。
例如:
+
声明为成员函数的二元运算符(例如)采用一个参数;如果声明为全局函数,它们有两个参数。重载的运算符不能有默认参数。
成员函数重载运算符的第一个参数始终是调用运算符的对象的类类型(声明运算符的类,或从该类派生的类)。没有为第一个参数提供转换。
但是没有关于返回类型的规则。因此,您可以从重载运算符返回任何类型。
推荐阅读
- quarkus - Quarkus - 如何在客户端使用密钥库与 TLS 建立 GRPC 会话?
- mysql - 更改正在运行的应用程序的 MySQL 字符编码
- mongodb - 如何配置 Debezium 的 MongoDB 源连接器以按照 Postgres JDBC 接收器连接器的预期发送 record_value 中的 pk 字段
- schema - 我在 shopify 中的哪里定义 @font-face?
- laravel - 在 Laravel 5.8 中显示存储目录中的图像
- sas - SAS如何根据条件制作sas代码
- ios - 按下视图控制器时不显示后退按钮
- python - 在 web 上使用 python 和 flask 呈现具有多个输入和输出的复杂决策流
- javascript - Javascript如何使回调返回一个值?
- azure - 我们可以为 azure 广告创建自定义用户定义声明吗?