问题描述
我有一个看起来像这样的遗留函数:
I have a legacy function that looks like this:
int Random() const
{
return var_ ? 4 : 0;
}
我需要调用旧代码中的函数,像这样:
and I need to call a function within that legacy code so that it now looks like this:
int Random() const
{
return var_ ? newCall(4) : 0;
}
问题是我收到此错误:
In member function 'virtual int Random() const':
class.cc:145: error: passing 'const int' as 'this' argument of 'int newCall(int)' discards qualifiers
现在我知道为了解决这个问题错误我可以使我的 newCall()
一个const函数。但是我有几个函数调用在 newCall()
,我必须做,所以现在我必须使所有的函数调用const。等等,直到最后我感觉像一半我的程序将是const。
Now I know in order to fix this error I can make my newCall()
a const function. But then I have several funciton calls in newCall()
that I have to make, so now I would have to make all of those function calls const. And so on and so forth until eventually I feel like half my program is going to be const.
我的问题:有没有什么方法来调用一个不是const的Random()函数?或者任何人都有任何想法如何实现 newCall()
在 Random()
,而不使我的程序const。
My question: is there any way to call a function within Random() that isn't const? Or does anyone have any ideas on how to implement newCall()
within Random()
without making half my program const.
感谢
-josh
推荐答案
您应该更改您的程序使用/正确声明const ...
you should alter your program to use/declare const correctly...
一个选择是使用const_cast 。
one alternative is to use const_cast.
这篇关于如何在const函数(C ++)中调用非const函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!