从非const对象调用const函数 [英] Calling a const function from a non-const object
问题描述
我需要从一个非const对象调用一个const函数。参见示例
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
我已经使用了
const_cast< const Bar *>(this) - > getProcess做一些工作();
这是骗局,但似乎过于复杂。
编辑:我应该提到该代码正在重构,最终只剩下一个函数。
const IProcess& getProcess()const
然而,目前有一个副作用,const调用可能返回一个不同的实例
p>避免转换:将它赋给
const Bar *
或其他任何东西,并使用它来调用 getProcess()
。 这有一些教条原因,但它也使它更明显你正在做什么,而不强制编译器做一些可能不安全的事情。假设,你可能永远不会碰到这些情况,但你也可以写一些在这种情况下不使用转换的东西。
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();
}
};
Calling
getProcess().doSomeWork();
will always results in a call to
IProcess& getProcess()
Is there another way to call
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.
Edit: I should mention that code is being refactored and eventually only one function will remain.
const IProcess& getProcess() const
However, currently there is a side effect and the const call may return a different instance of IProcess some of the time.
Please keep on topic.
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对象调用const函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!