当我的代码在函数范围之外时,为什么会出现编译器错误 "does not name a type"?
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);
}
"main.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
解释为一种类型。此外,将上面的代码包装在一个函数中(命名空间 foo
内的所有内容)允许它正确编译。
我有一道理论题和一道实用题:
- (理论) 为什么我的示例代码无法编译?
- (实用)我应该如何安排这段代码,以便它只为生成器播种一次?
只需改变前两个定义的顺序,并从种子构造生成器:
auto r_seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine r_gen(seed);
当我偶然发现这个我不明白的错误时,我正在测试我正在构建的游戏引擎,方法是在随机位置生成对象。
"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);
}
"main.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
解释为一种类型。此外,将上面的代码包装在一个函数中(命名空间 foo
内的所有内容)允许它正确编译。
我有一道理论题和一道实用题:
- (理论) 为什么我的示例代码无法编译?
- (实用)我应该如何安排这段代码,以便它只为生成器播种一次?
只需改变前两个定义的顺序,并从种子构造生成器:
auto r_seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine r_gen(seed);