gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:39:59 26 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




我正在制作一个运算符来比较我自己的类“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) getter 时”:方法恰好是 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 .
(这也适用于您的其他二传手。)

关于c++ - 运算符 const 参数不允许调用 const 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59844114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com