我可以给派生类中基类的成员取别名吗



假设我有以下类:

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关键字可以用于别名类型,也可以用于将受保护的基类成员带入公共范围。是否有类似的机制来对成员进行别名处理?

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
}

编辑:稍微有点麻烦的是,在构造函数的主体(即大括号内)之前,您无法初始化这些别名成员的值。

最新更新