问题描述
我正在尝试对多态项调用函数.但我在编译时收到以下错误消息:
I'm trying to call a function on a polymorphic item. But I get the following error message at compile time:
this
"参数的类型为const SelectParam
",但函数未标记为const
'
this
' argument to member function 'select
' has type 'const SelectParam
', but function is not markedconst
错误显示在 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 :-)
另一方面,如果 select
从不打算修改对象,只需将其标记为 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!