【问题标题】:C++ - Type mismatch error when initialising static private class memberC++ - 初始化静态私有类成员时出现类型不匹配错误
【发布时间】:2017-07-17 10:47:23
【问题描述】:

我有一个类,我希望能够静态生成自身的随机实例。为此,我有一个 std::uniform_real_distribution 的静态实例。但是,我在编译器中遇到类型不匹配错误。

编译器错误是:'genId' in 'class Foo' does not name a type'randId' in 'class Foo' does not name a type。但是,我已经在头文件中指定了类型,如下所示。

头文件(Foo.hpp):

class Foo {
public:
    static std::random_device rdId;
    static std::mt19937 genId;
    static std::uniform_real_distribution<> randId;
    // other code
}

实现文件(Foo.cpp):

#include "Foo.hpp"

Foo::genId = std::mt19937(Foo::rdId());
Foo::randId = std::uniform_real_distribution<>(0, 100);
// other code

我已经声明了类型,为什么会出现这个错误?

【问题讨论】:

  • 你也需要在实现文件中指定类型
  • @DanielJour 想知道为什么会这样?

标签: c++


【解决方案1】:

你需要指定类型:

std::mt19937 Foo::genId = std::mt19937(Foo::rdId());
std::uniform_real_distribution<> Foo::randId = std::uniform_real_distribution<>(0, 100);

【讨论】:

  • 谢谢@tuple_cat,当我已经在标头中声明类型并且“常规”成员不需要重复其类型时,是否有任何具体原因需要指定类型初始化了吗?
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多