【问题标题】:Can I alias a member of a base class in a derived class?我可以给派生类中的基类成员起别名吗?
【发布时间】:2012-12-09 04:44:24
【问题描述】:

假设我有以下课程:

template <class T>
class Base {
  protected:
    T theT;
    // ...
};

class Derived : protected Base <int>, protected Base <float> {
  protected:
    // ...
    using theInt = Base<int>::theT;     // How do I accomplish this??
    using theFloat = Base<float>::theT; // How do I accomplish this??
};

在我的派生类中,我想使用更直观的名称来引用Base::theT,这在派生类中更有意义。我使用的是 GCC 4.7,它很好地覆盖了 C++ 11 的特性。有没有办法使用using 语句来完成我在上面的示例中尝试的这种方式?我知道在 C++11 中,using 关键字可用于别名类型以及例如。将受保护的基类成员带入公共范围。有没有类似的机制给成员起别名?

【问题讨论】:

  • 我认为您要么需要引用,要么可能需要一个不会占用派生类空间的函数。 :|

标签: c++ c++11


【解决方案1】:

Xeo 的提示奏效了。如果您使用的是 C++ 11,则可以像这样声明别名:

int   &theInt   = Base<int>::theT;
float &theFloat = Base<float>::theT;

如果你没有C++11,我想你也可以在构造函数中初始化它们:

int   &theInt;
float &theFloat;
// ...
Derived() : theInt(Base<int>::theT), theFloat(Base<float>::theT) {
  theInt = // some default
  theFloat = // some default
}

编辑: 轻微的烦恼是,在构造函数的主体(即花括号内)之前,您无法初始化那些别名成员的值。

【讨论】:

  • 请注意,这会将派生类的大小增加sizeof(void*) 乘以引用数。这就是为什么我提出了一个名为 theXXX 的简单 getter 函数的建议。
  • 是的,我想你是对的。幸运的是,我认为额外的 8 个字节不会杀死我,因为我没有很多 Derived 类的实例,所以当我访问数据成员时,我可以坚持使用更易于键入的引用版本。跨度>
猜你喜欢
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 2021-11-15
  • 2020-12-24
  • 2011-08-26
  • 1970-01-01
  • 2011-11-10
相关资源
最近更新 更多