从非常量对象调用 const 函数

Calling a const function from a non-const object(从非常量对象调用 const 函数)
本文介绍了从非常量对象调用 const 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从非常量对象调用 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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)