gpt4 book ai didi

c++ - 来自 Stroustrup 的随机数示例存在编译错误

转载 作者:行者123 更新时间:2023-12-01 14:07:02 25 4
gpt4 key购买 nike

我正在使用 Stroustrup C++ 第 4 版第 1182 页的这个随机数示例。编译器在 auto 行报告错误。 ,说明 auto 不能与类的非静态成员一起使用。我对这种绑定(bind)的结果类型感到困惑。有谁知道如何解决错误以便可以使用随机数生成器?

#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;
}
编译错误:
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...
^~~~

最佳答案

您不能使用 auto对于类的非静态成员的类型,所以代码示例是错误的。
相反,您可以这样做:

class Rand_int {
private:
std::function<int()> r = bind(uniform_int_distribution<>{p},default_random_engine{});
// ...
};
这将转换 std::bind 的返回类型到返回 int 的 void 函数,这是所需的行为。
这是 demo .

关于c++ - 来自 Stroustrup 的随机数示例存在编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63303628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com