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

标签 c++

我正在使用 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/

相关文章:

用于 Linux 的 C++ IDE,具有智能引用搜索

c++ - MS SQL 存储过程使用 ODBC 返回结果集

c++ - 是否可以将 unordered_map 声明并初始化为函数参数?

c++ - "function()->"叫什么?

c++ - 为什么 C++ 不支持命名参数?

c++ - 异常处理和从非 fatal error 中恢复

c++ - 为什么我的 Active Directory 密码过滤器 DLL 中的用户名以 $ 结尾?

c++ - 如果我们删除 [-Wreturn-local-addr] 可以吗(警告 : address of local variable returned) by using static keyword in c++?

c++ - 如何分析 Rcpp 代码(在 Linux 上)

c++ - 交换类型列表中的两种类型