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

fin*_*ian 3 c++ polymorphism compiler-errors

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

this成员函数“ ”的参数“ select”具有类型“ const SelectParam”,但未标记函数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++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

最后是超级简单的父类。

class SelectParam {
    public:
    virtual const bool select( Tuple const & t) = 0;
};
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*tin 13

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

bool const select(Tuple const & tup) const {
Run Code Online (Sandbox Code Playgroud)


alt*_*gel 8

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

这意味着:

const SelectParam* ptr = whatever();
ptr->select(someTuple);
Run Code Online (Sandbox Code Playgroud)

是畸形的。

在你的情况下,你已经const SelectParam在这一行声明了一个指向 a 的指针:

for (const SelectParam* p: selectionParams) {
Run Code Online (Sandbox Code Playgroud)

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

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

virtual const bool select( Tuple const & t) const = 0;
Run Code Online (Sandbox Code Playgroud)

你的代码也应该工作。