我可以在派生类中为一个基类的成员设置别名吗?

Nic*_*rca 8 c++ c++11

说我有以下课程:

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??
};
Run Code Online (Sandbox Code Playgroud)

在我的派生类中,我想引用Base::theT一个更直观的名称,在Derived类中更有意义.我正在使用GCC 4.7,它具有很好的C++ 11功能.有没有办法使用一个using语句来完成我在上面的例子中尝试的这种方式?我知道在C++ 11中,using关键字可以用于别名类型以及例如.将受保护的基类成员带入公共范围.是否有类似的成员别名机制?

Nic*_*rca 7

Xeo的提示工作.如果您使用的是C++ 11,则可以像这样声明别名:

int   &theInt   = Base<int>::theT;
float &theFloat = Base<float>::theT;
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:轻微的烦恼是你不能初始化那些别名成员的值,直到构造函数的主体(即花括号内).

  • 请注意,这会通过`sizeof(void*)`乘以引用数来增加派生类的大小.这就是为什么我包含了一个名为`theXXX`的简单getter函数的建议. (4认同)