【发布时间】:2020-01-21 15:17:18
【问题描述】:
我正在制作一个运算符来比较我自己的类“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]
【问题讨论】:
-
你得到什么错误?
-
你的 getter 都不是 const。您忘记在函数名称后添加
const(const string & getNombre()->const string & getNombre() const)。投票结束是一个错字。 -
你说吸气剂是
const,但他们不是。你需要const string & getNombre() const {return nombre_;};等等。 -
您返回的是一个字符串常量,而不是函数常量。是不同的东西。
-
@NathanOliver,我会说这是重复的stackoverflow.com/questions/2157458/…,而不是离题
标签: c++