没有继承的公共成员

Public member without inheritance

本文关键字:成员 继承      更新时间:2023-10-16

我有一个基类,它看起来像这样:

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_twptr_tType。例如

Derived a;
a.x = Base::Type::foo; // this should work
a.x = Derived::Type::foo; // but I want this to fail

这可能吗,也许是friendvirtual之类的神奇用途?

只需覆盖类型:

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技术非常适合我的目的。