成员函数“select”的“this”参数的类型为“const SelectParam”,但函数未标记为 const

新手上路,请多包涵

我正在尝试在多态项上调用函数。但是我在编译时收到以下错误消息:

this const SelectParam 对成员函数的参数’ select const

错误显示在 p->selection(*it)

 std::set<Tuple>::iterator it;
for (it = tuples.begin(); it != tuples.end();) {
    for (const SelectParam* p: selectionParams) {
        bool successful = p->select(*it);
        if( !successful ) {
            it = tuples.erase(it);
        } else {
            it++;
        }
    }
}

以下是这些类的定义方式。 (我以前没有所有的 const 并且 & 在那里,但我把它们放在我能做的任何地方,希望我能做任何它想要的 const 但显然我没有解决这个问题,因为它没有改变任何东西。

在存储在父指针处的子类之一中。

 bool const select(Tuple const & tup) {
    bool matched = false;
    if (tup[idx] == val) {
        matched = true;
    }
    return matched;
}

在与多态一起使用的另一个子类中

bool const select(Tuple const & tup) {
    bool matched = false;
    if (tup[idx1] == tup[idx2]) {
        matched = true;
    }
    return matched;
}

最后是超级简单的父类。

 class SelectParam {
    public:
    virtual const bool select( Tuple const & t) = 0;
};

在此先感谢您愿意帮助我虚弱的大脑。

原文由 financial_physician 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 638
2 个回答

实际上,您不能将非 const 方法称为 const 对象。但是您也不能通过 指针或对 const 对象的引用调用非 const 方法(无论引用的对象是 const 还是)。

这意味着:

 const SelectParam* ptr = whatever();
ptr->select(someTuple);

格式不正确。

在您的情况下,您已在此行声明了指向 const SelectParam 的指针:

 for (const SelectParam* p: selectionParams) {

只需删除 const 它应该可以工作:-)

另一方面,如果 select 从不打算修改对象,只需将其标记为 const:

 virtual const bool select( Tuple const & t) const = 0;

你的代码也应该可以工作。

原文由 alter_igel 发布,翻译遵循 CC BY-SA 4.0 许可协议

您需要明确告诉编译器您的函数不会修改任何成员:

 bool const select(Tuple const & tup) const {

原文由 Martin Konrad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题