如何在 const 函数中调用非常量函数 (C++)
我有一个看起来像这样的旧函数:
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;
}
问题是我收到了这个错误:
The problem is that I'm getting this error:
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.
我的问题:有没有办法在 Random() 中调用不是 const 的函数?或者是否有人对如何在 Random()
中实现 newCall()
而不使我的程序一半成为常量有任何想法.
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.
谢谢
-乔什
推荐答案
你应该改变你的程序以正确使用/声明 const...
you should alter your program to use/declare const correctly...
另一种方法是使用 const_cast.
one alternative is to use const_cast.
相关文章