假设我有以下类(class):
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
关键字可用于别名类型以及例如。将 protected 基类成员带入公共(public)范围。是否有任何类似的机制来为成员起别名?
最佳答案
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
}
编辑: 有点烦人的是,直到构造函数的主体(即在大括号内),您才能初始化那些别名成员的值。
关于c++ - 我可以在派生类中为基类的成员起别名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13784734/