不允许运算符 const 参数调用 const 成员函数

operator const parameters not allowed to call const member functions

本文关键字:const 成员 函数 调用 参数 运算符 不允许      更新时间:2023-10-16

>im 制作一个运算符来比较我自己的类"Paciente"的对象,但是当调用该类的 (const( getter 时,我遇到了错误。 在这里我留下代码:

bool operator==(const Paciente& p1, const Paciente& p2){
return (p1.getNombre() == p2.getNombre() && p1.getApellidos() == p2.getApellidos());
}

这里是Paciente类:

class Paciente {
private:
string nombre_;
string apellidos_;
int edad_;
public:
Paciente(const string &nombre="none", const string &apellidos="none", const int &edad=0): nombre_(nombre), apellidos_(apellidos), edad_(edad){};
const string & getNombre(){return nombre_;};
const string & getApellidos(){return apellidos_;};
const int & getEdad() {return edad_;};
string setNombre(const string &nombre){nombre_ = nombre;};
string setApellidos(const string & apellidos){apellidos_ = apellidos;};
int setEdad(const int &edad){edad_ = edad;};
};

类 Paciente 在 'paciente.hpp' 分配,运算符和更多函数在 'functions.hpp' 分配。我知道这不是实现运算符的正确方法,但其他方法也出现了错误。谢谢。

编辑: 忘了提了,错误是:将"const Paciente"作为"this"参数传递会丢弃限定符[-fpermissive]

bool operator==(const Paciente& p1, const Paciente& p2)

这有两个常量对象作为参数。

但是,
const string & getNombre(){return nombre_;};
不是一个常量方法,因此不允许在常量对象上调用,这就是您尝试对p1.getNombre()执行的操作。
只需将其
更改为const string& getNombre() const { return nombre_; }.

为了详细说明这一点,因为你写了"但是当调用该类的(const(getters时":如果你像我一样声明一个方法,那么它就是const的。简单地说,在语义上不改变对象是不够的。编译器不够"聪明",无法检查语义,而且它真的不应该是错误的容易来源。
另请注意,它返回const string&不会使方法const。简单地想想像const string& iterate_one_step_and_return_status_string();
这样的
签名(是的,这是一个可怕的长名称,不应该使用(。

顺便说一下,方法实现末尾的分号不执行任何操作。仅当您仅声明而不实现时,才需要这些。
另外,我建议使用英语,除了价值观。在这种情况下,它并不那么重要,但是如果您发布的代码我们了解您想要做什么很重要,如果我们可以通过名称了解这一点,这将很有帮助。

编辑:我注意到您的代码的另一个问题:
string setNombre(const string &nombre){nombre_ = nombre;};此方法
具有返回类型string但不返回任何内容。我实际上想知道为什么您的编译器没有给您像Error: control may reach end of non-void function这样的警告或错误。
(这也适用于您的其他二传手。