2012-12-09 29 views
5

说我有以下类:我可以在派生类中为基类的成员别名吗?

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

我觉得你要么需要引用,要么可能是一个不会占用派生类空间的函数。 :| – Xeo

+0

谢谢,参考工作。 –

回答

6

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 
} 

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

+3

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

+0

是的,我想你是对的。幸运的是,我不认为额外的8个字节会杀死我,因为我没有很多Derived类的实例,所以当我访问数据成员时,我可以坚持使用易于使用的参考版本。 –

相关问题