会员复制方法

Max*_*xpm 5 c++ oop methods inheritance class-design

我有一个简单的低级容器类,由更高级别的文件类使用.基本上,在将最终版本保存到实际文件之前,文件类使用容器在本地存储修改.因此,某些方法直接从容器类传递到文件类.(例如,Resize().)

我刚刚在文件类中定义了方法来调用它们的容器类变体.例如:

void FileClass::Foo()
{
    ContainerMember.Foo();
}
Run Code Online (Sandbox Code Playgroud)

然而,这正在变得令人讨厌.有一个更好的方法吗?

这是一个简化的例子:

class MyContainer
{
    // ...

    public:

    void Foo()
    {
        // This function directly handles the object's
        // member variables.
    }
}

class MyClass
{
    MyContainer Member;

    public:

    void Foo()
    {
        Member.Foo();

        // This seems to be pointless re-implementation, and it's
        // inconvenient to keep MyContainer's methods and MyClass's
        // wrappers for those methods synchronized.
    }
}
Run Code Online (Sandbox Code Playgroud)

Xeo*_*Xeo 7

那么,为什么不直接继承MyContainer并通过using声明公开那些你想要转发的函数呢?这就是所谓的"执行MyClass 中的条款 MyContainer.

class MyContainer
{
public:
    void Foo()
    {
        // This function directly handles the object's
        // member variables.
    }

    void Bar(){
      // ...
    }
}

class MyClass : private MyContainer
{
public:
    using MyContainer::Foo;

    // would hide MyContainer::Bar
    void Bar(){
      // ...
      MyContainer::Bar();
      // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在"外部"将能够直接调用Foo,而Bar只能在内部访问MyClass.如果你现在创建一个具有相同名称的函数,它会隐藏基函数,你可以像这样包装基函数.当然,您现在需要完全限定对基本函数的调用,否则您将进行无休止的递归.


另外,如果你想允许(非多态)子类化MyClass,这是一个罕见的地方,受保护的继承实际上是有用的:

class MyClass : protected MyContainer{
  // all stays the same, subclasses are also allowed to call the MyContainer functions
};
Run Code Online (Sandbox Code Playgroud)

如果您MyClass没有虚拟析构函数,则为非多态.