9

假设我有以下课程:

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关键字可用于别名类型以及例如。将受保护的基类成员带入公共范围。有没有类似的机制来给成员起别名?

4

1 回答 1

8

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
}

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

于 2012-12-09T05:07:50.613 回答