Stroustrup中的随机数示例存在编译错误 我使用StruouStruC++第四ED页面1182的随机数例子。编译器在auto行上报告了一个错误,指出auto不能与类的非静态成员一起使用。我对这种绑定的类型感到困惑。有人知道如何解决错误,以便使用随机数生成器吗 #include <random> using namespace std; class Rand_int { public: // added Rand_int(int lo, int hi) : p{lo,hi} { } int operator()() const { return r(); } private: uniform_int_distribution<>::param_type p; auto r = bind(uniform_int_distribution<>{p},default_random_engine{}); }; int main() { Rand_int ri {0,10}; int pz = ri(); return 0; } #包括 使用名称空间std; 类Rand_int{ public://已添加 Rand_int(intlo,inthi):p{lo,hi}{ int运算符()()常量{return r();} 私人: 均匀分布:p型参数; 自动r=bind(统一分布{p},默认随机引擎{}); }; int main() { Rand_int ri{0,10}; int pz=ri(); 返回0; }

Stroustrup中的随机数示例存在编译错误 我使用StruouStruC++第四ED页面1182的随机数例子。编译器在auto行上报告了一个错误,指出auto不能与类的非静态成员一起使用。我对这种绑定的类型感到困惑。有人知道如何解决错误,以便使用随机数生成器吗 #include <random> using namespace std; class Rand_int { public: // added Rand_int(int lo, int hi) : p{lo,hi} { } int operator()() const { return r(); } private: uniform_int_distribution<>::param_type p; auto r = bind(uniform_int_distribution<>{p},default_random_engine{}); }; int main() { Rand_int ri {0,10}; int pz = ri(); return 0; } #包括 使用名称空间std; 类Rand_int{ public://已添加 Rand_int(intlo,inthi):p{lo,hi}{ int运算符()()常量{return r();} 私人: 均匀分布:p型参数; 自动r=bind(统一分布{p},默认随机引擎{}); }; int main() { Rand_int ri{0,10}; int pz=ri(); 返回0; },c++,C++,编译错误: clang++ -Wall -std=c++11 -pedantic test252.cc && ./a.out test252.cc:11:5: error: 'auto' not allowed in non-static class member auto r = bind(uniform_int_distribution<>{p},default_random_e... ^~~~ clang++-Wall-std=c++11-pe

编译错误:

clang++ -Wall -std=c++11 -pedantic test252.cc && ./a.out
test252.cc:11:5: error: 'auto' not allowed in non-static class member
    auto r = bind(uniform_int_distribution<>{p},default_random_e...
    ^~~~
clang++-Wall-std=c++11-pedantictest252.cc&./a.out
test252.cc:11:5:错误:非静态类成员中不允许“自动”
自动r=bind(统一分布{p},默认随机分布{p})。。。
^~~~

不能对类的非静态成员类型使用
auto
,因此代码示例是错误的

相反,您可以执行以下操作:

class Rand_int {
  private:
    std::function<int()> r = bind(uniform_int_distribution<>{p},default_random_engine{});
  // ...
};
class Rand\u int{
私人:
函数r=bind(统一分布{p},默认随机引擎{});
// ...
};
这将
std::bind的返回类型转换为返回int的void函数,这是所需的行为


这是一个.c/p>使用C++ 14编写的书符合C++ 11标准。这是迄今为止在任何C++标准中都无效的。我认为这个例子可能是在一个类之外设计的。@ Bathsheba——它是不允许的。默认成员初始化器在初始化成员初始化列表中时忽略了。那么成员应该有t类型吗?几乎不可能直观且一致地进行静态类型输入,同时仍然允许所有这些初始化形式。看起来像是书中的一个疏忽。根据

类Rand\u double
的示例进行改编。我认为bind创建了一个传递参数的函数,
default\u randoom\u engine()
在这种情况下,
int()
函数类型?否,
bind
精确地绑定了
default\u random\u引擎
参数,因此它可以无参数调用。请查看它在
operator()
中的用法。