c++ - 封装子类

标签 c++

我有一堆类 Bar1Bar2 等,它们都共享一个公共(public)父类 Foo。我想完全隐藏它们并仅通过 Foo 的虚方法提供的接口(interface)访问它们。我试图将它们嵌套为 Foo 的私有(private)类,如下所示:

class Foo
{
    public:
        Foo ();
        static Foo *MakeBar (int someParams);

    private:
        class Bar1 : public Foo
        {
            Bar1 () : Foo () {}
        };

        class Bar2 : public Foo
        {
            Bar2 () : Foo () {}
        };

        // etc
};

但是,这是不可能的,因为在声明类 Bar1 时类 Foo 是不完整的。有没有其他方法可以防止直接访问子类?

最佳答案

尝试将继承类从类声明移动到实现单元中的未命名命名空间。像这样:

foo.h

class Foo
{
public:
    Foo ();
    static Foo *MakeBar (int someParams);
};

foo.cpp

#include "foo.h"

namespace {

class Bar1 : public Foo
{
      Bar1 () : Foo () {}
};

class Bar2 : public Foo
{
      Bar2 () : Foo () {}
};

} // endof unnamed namespace

Foo *Foo::MakeBar (int someParams)
{
    // do stuff here
}

关于c++ - 封装子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27441984/

相关文章:

android - Android NDK 上的谷歌测试未定义对 'typeinfo for testing::Test' 的引用

c++ - Push.back into vector behavior maybe or something wrong with my for statement?

c++ - 如何在我的特定代码中实现动态位集

c++ - volatile 功能

c++ - 为设备编译 Boost 1.54 XCode5 - fatal error : error in backend: symbol '___umodsi3' can not be undefined in a subtraction expression

c++ - 从 Poco http 客户端获取对字符串的响应

c++ - 在编译时检查销毁顺序约束

c++ - 为什么使用 Visual Studio 和命令行编译时大小不同

c++ - 应用于变量名时 * 和 & 的含义是什么?

c++ - MultiByteToWideChar 转换