【问题标题】:Why the `using` keyword cannot be used for static class member?为什么`using`关键字不能用于静态类成员?
【发布时间】:2020-11-15 19:15:12
【问题描述】:

using 使标识符在全局范围内可见,但为什么不能用于static 类成员?

例如using std::string::size_type; 是错误的。为什么?

【问题讨论】:

    标签: c++ class c++11 static using


    【解决方案1】:

    为什么不能用于static类成员?

    你误解了using-declaration的用法

    Using-declarations 可用于将 命名空间成员引入 other namespaces and block scopes,或引入基类 成员到派生类定义中

    std::string::size_type; 是在std::string 类中定义的member type,而不是任何命名空间中的命名空间或函数。

    因此,对于using,您只能指定/声明alias type for a type。例如:

    using string_size_type = std::string::size_type;
    

    【讨论】:

    • 例如“struct Test { static int a;}; using Test::a;”
    • 那么有什么办法可以在没有 :: 运算符的情况下提及静态类成员?
    • @AlanJian 我已经更新了答案。对于类的静态成员,这是不可能的。但对于任何命名空间范围内的函数,这可能是:godbolt.org/z/xWM551
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    相关资源
    最近更新 更多