首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用-从基类中声明现有类型与在子类中创建类型别名

使用-从基类中声明现有类型与在子类中创建类型别名
EN

Stack Overflow用户
提问于 2019-10-18 10:31:04
回答 1查看 253关注 0票数 0

我想从子类中的基类中提供对现有类型的访问。

我发现了两种不同的方法:

代码语言:javascript
运行
复制
struct A {
    typedef int mytype;
};

struct B {
    typedef double mytype;
};

我可以“包括”带有using声明的类型:

代码语言:javascript
运行
复制
struct C : A, B {
    using typename A::mytype;
};

或者我可以创建一个类型别名:

代码语言:javascript
运行
复制
struct C : A, B {
    typedef A::mytype mytype;
    using mytype = A::mytype; //C++11
};

  1. 有什么区别吗?
  2. 每种语法的优缺点是什么?
  3. 是最常用的/推荐的?

谢谢。

相关问题:Using-declaration of an existing namespace type vs creating a type alias

EN

回答 1

Stack Overflow用户

发布于 2019-10-18 12:23:52

是有区别的。如果您的结构A和B被定义为:

代码语言:javascript
运行
复制
struct A {
protected:
    int mytype;
};

struct B {
protected:
    double mytype;
};

在这种情况下

代码语言:javascript
运行
复制
struct C : A, B {
    using typename A::mytype;  // Would compile, but is mytype a type or
                               // an exposed member of the base class?
    //using mytype = A::mytype;  // Would not compile
};

在您的情况下,我建议使用using mytype = A::mytype;,因为它不太含糊。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58449034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档