我可以在派生类中对基类的成员进行别名吗? [英] Can I alias a member of a base class in a derived class?

查看:182
本文介绍了我可以在派生类中对基类的成员进行别名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下类:

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 使用更直观的名称,这在Derived类中更有意义。我使用GCC 4.7,它有相当不错的C ++ 11功能的覆盖。是否有一种方法使用使用语句来完成这种我在上面的示例中尝试的方式?我知道在C ++ 11中,使用关键字可以用于别名类型以及eg。使受保护的基类成员进入公共范围。是否有类似的机制用于别名成员?

In my derived class, I would like to refer to Base::theT using a more intuitive name that makes more sense in the Derived class. I am using GCC 4.7, which has pretty good coverage of C++ 11 features. Is there a way of using a using statement to accomplish this kind of how I tried in my example above? I know that in C++11, the using keyword can be used to alias types as well as eg. bring protected base class members into the public scope. Is there any similar mechanism for aliasing a member?

推荐答案

Xeo的提示工作。如果你使用的是C ++ 11,你可以这样声明别名:

Xeo's tip worked. If you are using C++ 11, you can declare the aliases like so:

int   &theInt   = Base<int>::theT;
float &theFloat = Base<float>::theT;

如果你没有C ++ 11,我想你也可以在构造函数中初始化它们:

If you don't have C++11, I think you can also initialize them in the constructor:

int   &theInt;
float &theFloat;
// ...
Derived() : theInt(Base<int>::theT), theFloat(Base<float>::theT) {
  theInt = // some default
  theFloat = // some default
}

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

The slight annoyance is that you can't initialize the the value of those aliased members until the main body of the constructor (ie, inside the curly braces).

这篇关于我可以在派生类中对基类的成员进行别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆