How to call a non-const function within a const function (C++)

陌路散爱 提交于 2019-11-27 05:54:10

问题


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

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.

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.

Thanks

-josh


回答1:


you should alter your program to use/declare const correctly...

one alternative is to use const_cast.




回答2:


int Random() const
{
  return var_ ? const_cast<ClassType*>(this)->newCall(4) : 0;
}

But it's not a good idea. Avoid if it's possible!




回答3:


const_cast<MyClass *>(this)->newCall(4)

Only do this if you're certain newCall will not modify "this".




回答4:


There are two possibilities here. First, newCall and ALL of its callees are in fact non-modifying functions. In that case you should absolutely go through and mark them all const. Both you and future code maintainers will thank you for making it much easier to read the code (speaking from personal experience here). Second, newCall DOES in fact mutate the state of your object (possibly via one of the functions it calls). In this case, you need to break API and make Random non-const to properly indicate to callers that it modifies the object state (if the modifications only affect physical constness and not logical constness you could use mutable attributes and propagate const).




回答5:


Without using const casts, could you try creating a new instance of the class in the Random() method?




回答6:


The const qualifier asserts that the instance this of the class will be unchanged after the operation, something which the compiler cant automagically deduce.

const_cast could be used but its evil




回答7:


if it's really a random number generator, then the number generation code/state could likely be placed in a class-local static generator. this way, your object is not mutated and the method may remain const.



来源:https://stackoverflow.com/questions/5008541/how-to-call-a-non-const-function-within-a-const-function-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!