问题描述
我需要从非常量对象调用 const 函数.看例子
I need to call a const function from a non-const object. See example
struct IProcess {
virtual bool doSomeWork() const = 0L;
};
class Foo : public IProcess {
virtual bool doSomeWork() const {
...
}
};
class Bar
{
public:
const IProcess& getProcess() const {return ...;}
IProcess& getProcess() {return ...;}
void doOtherWork {
getProcess().doSomeWork();
}
};
打电话
getProcess().doSomeWork();
总会导致调用
IProcess& getProcess()
还有其他方法可以调用
const IProcess& getProcess() const
来自一个非常量的成员函数?到目前为止我用过
from a non constant member function? I have so far used
const_cast<const Bar*>(this)->getProcess().doSomeWork();
这可以解决问题,但似乎过于复杂.
which does the trick but seems overly complicated.
我应该提到代码正在重构,最终只剩下一个函数.
I should mention that code is being refactored and eventually only one function will remain.
const IProcess& getProcess() const
但是,目前存在副作用,有时 const 调用可能会返回不同的 IProcess 实例.
However, currently there is a side effect and the const call may return a different instance of IProcess some of the time.
请继续话题.
推荐答案
避免强制转换:将其分配给 const Bar *
或其他任何东西并使用它来调用 getProcess()代码>.
Avoid the cast: assign this to a const Bar *
or whatever and use that to call getProcess()
.
这样做有一些迂腐的理由,但它也可以让你在不强制编译器做一些可能不安全的事情的情况下更清楚地知道你在做什么.诚然,您可能永远不会遇到这些情况,但您不妨编写一些在这种情况下不使用强制转换的东西.
There are some pedantic reasons to do that, but it also makes it more obvious what you are doing without forcing the compiler to do something potentially unsafe. Granted, you may never hit those cases, but you might as well write something that doesn't use a cast in this case.
这篇关于从非常量对象调用 const 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!