没有继承的公共成员

时间:2011-06-15 03:07:58

标签: c++ oop inheritance friend

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

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或类似的东西?

3 个答案:

答案 0 :(得分:4)

只需覆盖类型:

class Derived {
  typedef int Type;
};

它将not allow the use of Derived::Type(因为它是私有的以及typedef ed)

答案 1 :(得分:3)

class Derived : public Base
{
  // This is now private
  using Base::ptr_t;
  using Base::wptr_t;
  // ...
};

答案 2 :(得分:0)

根据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技术很适合我的目的。