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

Declaring an object of random class in class definition

本文关键字:对象 随机 定义 声明      更新时间:2023-10-16

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

这是我试图完成的示例。 "例子.h">

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

"例子.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

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

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

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

成员初始值设定项列表直接在函数签名放置之后工作 :成员名称(构造函数操作数( 如果要初始化多个成员,只需用逗号分隔它们。