小编Fai*_*ght的帖子

将成员函数放在定义中

我正在将许多常用函数转移到类中,但遇到了我无法解释的障碍。通过全局空间中的“STD::random-device rd”和“std::mt19937 gen(rd())”声明,一切正常。

include <random>

std::random_device rd;
std::mt19937 gen(rd());

class randomGenerator
{
public:

    float getRandomFloat(float lowerLimit, float upperLimit)
    {
        std::uniform_real_distribution<>dist(lowerLimit, upperLimit);
        return (float)dist(gen);
    }
};
randomGenerator myGenerator;
Run Code Online (Sandbox Code Playgroud)

但是如果我将声明移到类定义中,编译器会抱怨......

include <random>

class randomGenerator
{
public:
    std::random_device rd;
    std::mt19937 gen(rd());
    float getRandomFloat(float lowerLimit, float upperLimit)
    {
        std::uniform_real_distribution<>dist(lowerLimit, upperLimit);
        return (float)dist(gen);
    }
};
randomGenerator myGenerator;
Run Code Online (Sandbox Code Playgroud)

"E0757 member "randomGenerator::rd" is not a type name""E0304 no instance of overloaded function "std::uniform_real_distribution<_Ty>::operator() [with _Ty=double]" matches the argument list"

我在将独立变量声明移动到其他类时也遇到了类似的麻烦;看起来几乎是碰碰运气。有什么原因导致这并不总是有效吗?我不明白为什么某些声明(如上面)只能在全局空间中起作用。

c++ class class-members

3
推荐指数
1
解决办法
85
查看次数

标签 统计

c++ ×1

class ×1

class-members ×1