0

我试图只使用基类的特定部分,而隐藏其他部分。考虑以下代码:

struct IX
{
    // ...
};

struct IY
{
    // ...
};

class Base :
    public IX,
    public IY
{
    // Implements IX and IY.
    // ...
};


// Reuse IX implementation, but don't expose IY.
//
class X : protected Base
{
public:
    using Base::IX; // <-- Doesn't exist in C++.
};

我可以享受由IX提供的实现Base,但不暴露IY接口吗?

当然,我可以输入using Base::IX::xxx所有存在于IX. 或者,我可以像这样将所有调用转发到实现:

//
class X : public IX
{
public:
    // Forward all calls to IX methods to m_p.
    // ...

protected:
    Base* m_p;
};

但同样,我必须键入所有可用的方法IX才能转发它们。而且每次IX更改,我都必须更新X.

谢谢。

亚历克斯

4

1 回答 1

0

好吧,基本上实现IXIY在您的class X. 您可以在类中将访问器和修饰符公开为公共方法。

另一种方法是从 Base 公开 IX:

class Base : public IX, protected IY
{
    // Implements IX and IY.
    // ...
    // Expose access to IY through base for the class 
    // inheriting from Base
};

class X : public Base 

另一种可能性是不继承IXIY而是将它们保留为您的公共成员Base

class Base
{
public:
    IX member1;
    IY member2;
};

这样,您可以从 Base 受保护地继承,并且可以从您的class Xfor公开单个访问器和修饰符方法member1

于 2012-11-12T06:33:38.653 回答