c++ - 我可以在派生类中为基类的成员起别名吗?

标签 c++ c++11

假设我有以下类(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/

相关文章:

javascript - Qt webkit编程,Qt数据类型对应Javascript数据类型是什么?

c++ - c++中的*const*a是什么意思

c++ - 使用带有动态库的 Eigen 和 Visual Studio 2013 的内存对齐错误

c++ - C++11 中的线程移动

c++ - Google基准测试夹具:跨多个基准测试的重用 vector

c++ - 使用 `for(auto& e : cont)` 安全吗? vector<bool> 有什么问题?

C++ 原子加载排序效率

c++ - 从 Lua 中提取变量到 C++

c++ - 可变参数模板的罕见错误?

c++ - 如果在生成 std​​::thread 后引发异常,则未捕获异常