在类定义中声明一个随机类的对象

问题描述 投票:-1回答:1

所以,我正在编写一个类,我需要生成从均匀分布中采样的随机数。由于我需要经常生成随机数,我想在类定义中创建一个对象。

这是我想要完成的例子。 “example.h文件”

class ABC
{
  public:
   ABC();
   /* code goes here */
  private:
   std::mt19937 mt(std::random_device rd;);
   std::uniform_int_distribution<int> dist;
}

“example.cpp”

ABC::ABC():ABC::dist(0,12)
{
  /* ABC class constructor */
}

上面的代码没有编译。任何人都可以帮助或指出错误。提前致谢。以下错误由g ++编译器生成。

src/tsim.cpp: In constructor ‘TrafficSim::TrafficSim(bool, float)’:
src/tsim.cpp:5:71: error: expected class-name before ‘(’ token
 TrafficSim::TrafficSim(bool render,float time_period):TrafficSim::dist(0,110)
                                                                       ^
src/tsim.cpp:5:71: error: expected ‘{’ before ‘(’ token
src/tsim.cpp: At global scope:
src/tsim.cpp:5:72: error: expected unqualified-id before numeric constant
 TrafficSim::TrafficSim(bool render,float time_period):TrafficSim::dist(0,110)
                                                                        ^
src/tsim.cpp:5:72: error: expected ‘)’ before numeric constant
c++ linux c++11 g++
1个回答
0
投票

您错误地定义了构造函数。

为了定义成员初始化列表,您需要将其定义为

ABC::ABC() : dist(0, 12)
{
  /* ABC class constructor */
}

成员初始化列表直接在函数签名后执行:memberName(构造函数操作数)如果要初始化多个成员,只需用逗号分隔它们即可。

© www.soinside.com 2019 - 2024. All rights reserved.