【问题标题】:operator const parameters not allowed to call const member functions [closed]运算符 const 参数不允许调用 const 成员函数
【发布时间】: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++


【解决方案1】:

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这样的警告或错误。
(这也适用于您的其他二传手。)

【讨论】:

  • 很好,回答,因为我们只能在 const 对象上调用 const 方法,因为这些对象是只读的,除非它们具有可变数据成员,否则不应更改
  • ...此时只能更改那些可变变量。这就是mutable 的用途。而mutable 主要用于“惰性求值” getFoo():当返回值不会改变,但您还没有确定该值是什么时。例如:一个类有int a, b, mutable sum。每次有人调用 getSum() 时,您不必所有这些工作添加几个整数,而是仅在它更改然后查询时计算它,并设置可变的@987654335 @,所以它可以重复使用。当某些值可能永远不会被查询,而某些值可能会被重复查询时,这很好。
猜你喜欢
  • 2011-06-04
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多