不允许运算符 const 参数调用 const 成员函数
operator const parameters not allowed to call const member functions
>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
这样的警告或错误。
(这也适用于您的其他二传手。
- 不允许运算符 const 参数调用 const 成员函数
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- 如何避免将 const 和非 const 成员函数输入到模板中的代码重复
- 初始化 const 成员的正确方法
- 使用 Boost 对具有 const 成员的类进行序列化
- 非常量调用 const 成员函数失败,只读位置C++
- PIMPL类的设置应该是const成员函数
- 与其他静态const成员初始化静态常量成员
- decltype 不会推断 const 对象的 const 成员
- 如何初始化不是静态的const成员
- 如何使用常量变量初始化类的 const 成员变量
- 使用模板参数初始化静态 const 成员
- 与const成员配对的向量
- 通过参考const成员通过参考时,尝试引用已删除的函数
- const成员初始化之前的用法是GCC和Clang的这种预期行为
- 通过const成员变量访问内联函数
- 与const成员一起安排新的和班级的分配
- 在const函数中调用非CONST成员的非const函数
- 为什么即使对于 "copy on write" 的 const 成员函数也返回一个代理类?