c++ - 没有继承的公共(public)成员

标签 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 仍然是一个基指针。我希望 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;
};

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

关于c++ - 没有继承的公共(public)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6352606/

相关文章:

c++ - 在运行时管理共享库之间的 Boost::any

php - PHP 中使用外键的 ORM 设计

java - 实例字段的继承如何在此特定代码中工作?

c++ - 如何从继承的父类创建 unique_ptr

JavaScript 原型(prototype)父类(super class)

c++ - std::set 自定义比较器用于 2D 点

c++ - const 与引用传递一起使用有什么意义? C++

c++ - (C++)我正在尝试从文本文件读取和输出随机行,并且在运行它时不断获取 “Floating Point Exception (Core Dumped)”

javascript - 做点什么并继续上课

java - 如何从委托(delegate)方法的类创建对象?