没有继承的公共成员
Public member without inheritance
我有一个基类,它看起来像这样:
class Base
{
public:
typedef std::shared_ptr<Base> ptr_t;
typedef std::weak_ptr<Base> wptr_t;
enum class Type { foo, bar, baz };
Type x;
// ...
};
我希望这些内部类型是公共的,这样我就可以做Base::ptr_t my_ptr(new Base);
之类的事情。但如果我创建一个这样的新类。。。
class Derived : public Base
{
// ...
};
不幸的是,Derived::ptr_t
仍然是一个Base指针。我希望Derived从Base公开继承x
,但不继承ptr_t
、wptr_t
或Type
。例如
Derived a;
a.x = Base::Type::foo; // this should work
a.x = Derived::Type::foo; // but I want this to fail
这可能吗,也许是friend
或virtual
之类的神奇用途?
只需覆盖类型:
class Derived {
typedef int Type;
};
它将不允许使用Derived::Type
(因为它是私有的,也是typedef
ed)
class Derived : public Base
{
// This is now private
using Base::ptr_t;
using Base::wptr_t;
// ...
};
根据iammilind和Luc Danton的回答,我得出了以下结论:
class Base
{
private:
// only 'BaseClass' is allowed to derive from Base
Base() { }
friend class BaseClass;
public:
typedef std::shared_ptr<Base> ptr_t;
typedef std::weak_ptr<Base> wptr_t;
enum class Type { foo, bar, baz };
Type x;
// ...
};
class BaseClass : public Base
{
private:
// make all the raw_Base types private
using Base::ptr_t;
using Base::wptr_t;
using Base::Type;
};
class Derived : public BaseClass
{
// define as usual, and now all is well in the world.
};
// now, to test it
class Derived2 : public Base { }; // fails
Derived d;
d.x = Derived::Type::foo; // fails
d.x = Base::Type::foo; // works
// Which is exactly what I wanted.
据我所知,这个解决方案的唯一问题是它添加了一个新的、可能会混淆的类。该类的定义方式使得它不会被真正滥用——Base
本身除了由BaseClass
派生之外,不能从中派生,但BaseClass
仍然是一个没有吸引力的名称空间混乱部分。
然而,对于我打算在其中使用的特定代码段,我碰巧已经在使用等效的BaseClass
来解决一个不相关的问题。所以这个BaseClass
技术非常适合我的目的。
相关文章:
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 如何从另一个文件继承私有成员变量和公共函数
- C++继承更改成员
- 继承和友元函数,从基类访问受保护的成员
- 删除C++继承中虚拟类成员的代码重复
- 成员包含其他继承类的继承类?
- 如何定义一个没有重复代码的继承的 const 类成员函数?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- enable_if继承的成员函数的名称查找错误
- 初始化依赖于子类的继承类的常量类成员
- 继承:调用基类的成员和方法
- 类设计:类成员继承自同一基类
- 使用 CRTP 进行选择性静态成员继承
- 具有'using'的模板模板成员继承
- 结构绑定:与公共数据成员(继承的基类)结合
- 为什么C++继承不允许基类的公共成员继承到派生类的私有成员?
- 静态成员继承和保护
- 是否可以检查是否为类定义了成员函数,即使该成员继承自未知基类
- 混合模板/非模板继承分类和成员继承