开发者

c++ multiple inheritance function merging

开发者 https://www.devze.com 2023-04-11 03:32 出处:网络
I have: class XILightSource { public: virtual XVec2 position() const = 0; }; class XLightSprite : public XSprite, public XILightSource

I have:

class XILightSource 
{
public:
    virtual XVec2 position() const = 0;
};

class XLightSprite : public XSprite, public XILightSource
{

};

The problem is that XSprite already has the same function position. How can i say to compiler, that i want to开发者_运维问答 use XSprite::position function as an implementation of XILightSource::position() ?


override it and call XILightSource::position() :

class XLightSprite : public XSprite, public XILightSource
{
  public:
     XVec2 position() const { return  XSprite::position(); }
};


Just add one line:

class XLightSprite : public XSprite, public XILightSource
{
 public:
    using XSprite::position;
};


Actually, you do not need to do anything special.

By default, implementing a XVec2 position() const in XLightSprite will hide the position() of XSprite and act as an override of the virtual function defined in XLightSource.

If, however, you want to clarify that your intent is to override the function, you can add a using declaration

class XLightSprite : public XSprite, public XILightSource
{
 public:
    using XSprite::position;
    XVec2 position() const;
};

Please note, however, that if the position() from XSprite is also a virtual function on the same format, the new implementation will also act as an override of the position in XSprite.


If class XSprite already has that function then the best way is to make XSprite a child of XILightSource (since it's abstract). The advantage of this approach is that you don't have to rely on multiple inheritance unnecessarily. i.e.

class XILightSource 
{
public:
  virtual XVec2 position() const = 0;
};

class XSprite : public XILightSource
{
public:
  virtual XVec2 position() const { ... }
};

class XLightSprite : public XSprite
{
};
0

精彩评论

暂无评论...
验证码 换一张
取 消