我正在对C ++第四版127-130页中的随机数使用Stroustrup的C ++示例进行小的修改。
我在修改下面第130页上的示例以使用非确定性随机种子时遇到麻烦。在re{rd}
s构造函数中添加代码Rand_int
时收到警告。我已包含警告,但不确定警告的含义或解决方法。有人知道吗?
使用非确定性随机数的第130页修改的代码:
#include <random>
#include <iostream>
#include <functional>
using namespace std;
class Rand_int {
public:
Rand_int(int low, int high) :dist{low,high}, re{rd()} { }
int operator()() { return dist(re); } // draw an int
private:
random_device rd;
default_random_engine re;
uniform_int_distribution<> dist;
};
int main(int argc, char *argv[])
{
Rand_int rnd {1, 6};
vector<int> hist(7);
for (int i=0; i<200; i++)
++hist[rnd()];
for (size_t i=1; i<hist.size(); i++) {
cout << i << '\t';
for (int j=0; j!=hist[i]; ++j)
cout << '*';
cout << endl;
}
return 0;
}
警告:
test93.cc:13:32: warning: ‘Rand_int::dist’ will be initialized after [-Wreorder]
uniform_int_distribution<> dist;
^~~~
test93.cc:12:27: warning: ‘std::default_random_engine Rand_int::re’ [-Wreorder]
default_random_engine re;
^~
test93.cc:8:5: warning: when initialized here [-Wreorder]
Rand_int(int low, int high) :dist{low,high}, re{rd()} { }
^~~~~~~~
1 ********************************
2 *********************************
3 *************************************
4 ****************************************
5 ********************************
6 **************************
来自页面127和128的代码用于生成不确定的随机数:
#include <random>
#include <iostream>
#include <functional>
using namespace std;
int main(int argc, char *argv[])
{
using engine = default_random_engine;
using distribution = uniform_int_distribution<>;
random_device rd; // for seed
engine re{rd()};
distribution dist {1,6};
auto rand = bind(dist, re);
vector<int> hist(7);
for (int i=0; i<200; i++)
++hist[rand()];
for (size_t i=1; i<hist.size(); i++) {
cout << i << '\t';
for (int j=0; j!=hist[i]; ++j)
cout << '*';
cout << endl;
}
return 0;
}
类的成员将按照声明的顺序进行初始化,无论您在成员初始化器列表中对其进行初始化的顺序如何。编译器错误非常具体,并指出您应编写:
Rand_int(int low, int high) : re{rd()}, dist{low,high} { }
编译器告诉您,Rand_int
的数据成员将按照声明的顺序初始化(rd
,然后是re
,然后是dist
),但是这与以下顺序不匹配:您已在构造函数的初始化程序列表中指定了它们:
dist{low,high}, re{rd()}
此警告旨在提醒您以下事实:即使您以相反的顺序指定了re
,也会在dist
之前对其进行初始化。要解决此问题,只需对初始化列表进行重新排序:
re{rd()}, dist{low,high}