【问题标题】:Abbreviate the full name of a type defined in a class类中定义的类型全名的缩写
【发布时间】:2016-02-09 03:46:01
【问题描述】:

当我使用类中定义的类型时,避免编写类名的最佳方法是什么?

例如,我有一个 MyClass 类,其中定义了 mytype 类型,在这个类中我需要使用 mytype 并且我必须写:

MyClass::mytype foo

我只想写

mytype foo

我试过了

#define MyClass::mytype mytype

它有效,但我认为这不是一个好的解决方案。我应该使用什么?

【问题讨论】:

  • 取决于您的方案auto my_value = ...typedef MyClass::mytype mytypeusing mytype = MyClass::mytype,但绝不是#define ...

标签: c++


【解决方案1】:

你可以这样做:

typedef MyClass::mytype mytype;

【讨论】:

  • 哈,你快了 15 秒 :)
  • PreferenceBean 快了两年:P,@MarcusMüller。
  • @Zeta: 很好看!我应该认为这太明显了以至于没有被问到。
【解决方案2】:

使用 typedef 或别名声明,最好在尽可能窄的范围内。

void some_function() {
    typedef MyClass::mytype mytype;
    // or: using mytype = MyClass::mytype;
}
// namespace not polluted

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2019-06-21
    • 2013-01-23
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多