本文介绍了成员函数'select'的'this'参数类型为'const SelectParam',但函数未标记为const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to call a function on a polymorphic item. But I get the following error message at compile time:

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

the error is shown at the 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,但显然我没有解决问题,因为它没有改变任何东西。

and here's how those classes are defined. (I use to not have all the const and & is there but I put them everywhere I could in hopes that I would make whatever it wanted const but clearly I'm not approaching the problem right since it's not changing anything.

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

In one of the child classes that is being stored at parent pointer.

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

在另一个用于多态的子类中

In the other child class that is being used with polymorphism

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

最后是超级简单的父类。

And finally here's the parent class that's super simple.

class SelectParam {
    public:
    virtual const bool select( Tuple const & t) = 0;
};
``
Thanks in advance for being willing to help my feeble brain.


推荐答案

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

Indeed, you cannot call a non-const method a const object. But you also cannot call a non-const method through a pointer or reference to a const object (regardless of whether the referred-to object is const or not).

这意味着:

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

格式错误。

在您的案例,您已经在此行上声明了指向 const SelectParam 的指针:

In your case, you've declared a pointer to a const SelectParam here on this line:

for (const SelectParam* p: selectionParams) {

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

Simply remove the const and it should work :-)

另一方面,如果选择绝不意味着修改对象,只需将其标记为const:

On the other hand, if select is never meant to modify the object, simply mark it as const:

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

您的代码也应该可以使用。

And your code should also work.

这篇关于成员函数'select'的'this'参数类型为'const SelectParam',但函数未标记为const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:06