[英]Why do I get the compiler error “does not name a type” when my code is outside of a function scope?
当我偶然发现这个我不理解的错误时,我正在通过在随机位置生成对象来测试我正在构建的游戏引擎。
“foo.h”:
#include <random>
#include <chrono>
#include <functional>
namespace foo {
std::default_random_engine r_gen;
auto r_seed = std::chrono::system_clock::now().time_since_epoch().count();
r_gen.seed(r_seed); // This is the line giving an error
std::uniform_real_distribution<float> r_dist(-1.0, 1.0);
auto r_float = std::bind(r_dist, r_gen);
}
“主.cpp”:
#include <iostream>
#include "foo.h"
int main() {
// Actually run the program
}
尝试编译此代码会给我错误消息:
error: 'r_gen' does not name a type
r_gen.seed(r_seed);
^~~~~
我将 Eclipse 与 MinGW 一起使用。 我不确定它为什么将r_gen
解释为一种类型。 此外,将上述代码包装在 function (命名空间foo
中的所有内容)中可以使其正确编译。
我有一个理论问题和一个实用问题:
只需更改前两个定义的顺序,并从种子构造生成器:
auto r_seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine r_gen(seed);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.