如何在 const 函数中调用非常量函数 (C++) [英] How to call a non-const function within a const function (C++)

查看:22
本文介绍了如何在 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.

这篇关于如何在 const 函数中调用非常量函数 (C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆