【问题标题】:Error in using static function in struct in namespace. (c++)在命名空间的结构中使用静态函数时出错。 (c++)
【发布时间】:2020-07-25 15:43:12
【问题描述】:

我有这段代码,我在命名空间中创建了带有静态函数的结构:

namespace Hashing {
    ///...
    struct Hash {
        ///...
        static void init(int n, const ull m = 31ull) {
             ///...
        }
    };
    ///...
}

我在 main 中使用以下代码:

int main() {
    ///...
    Hashing::Hash.init(12);
    ///...
}

发生错误:

error: expected unqualified-id before '.' token
  Hashing::Hash.init(12);
               ^

这是为什么呢?

【问题讨论】:

    标签: c++ oop static namespaces


    【解决方案1】:

    将其更改为:Hashing::Hash::init(12);。静态成员函数不与任何对象关联。

    【讨论】:

    • 哦哦。我怎么可能没有注意到呢?
    • @ВасилийПупкин 你会惊讶于你会错过什么。我三个星期都找不到手电筒,因为有人把它从微波炉的顶部移到了微波炉旁边,最多只有一英尺远。
    【解决方案2】:

    使用:: 调用静态方法,例如Hash::init()

    使用. 用于成员函数和变量。 Hash 类不是成员,但 Hash h 会。

    【讨论】:

      【解决方案3】:

      . 应该是 ::

      修改后的代码:

      #include <iostream>
      namespace Hashing{
        struct Hash{
          static void print(int num){
            std::cout<<num<<"\n";
          }
        };
      }
      int main() {
        Hashing::Hash::print(12);
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-22
        • 2016-09-11
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 2010-09-14
        相关资源
        最近更新 更多