c++ - 如何使用 uniform_int_distribution 作为构造函数中的类字段

标签 c++ class

如何使用 uniform_int_distribution 作为构造函数中的类字段。我是++ 的新手。我正在尝试下一种方法,但遇到了错误。

class RandomConnectionsProvider : RandomProviderBase
{
public:
    RandomConnectionsProvider(mainDataType operatorsCount);
    ~RandomConnectionsProvider(void);
    static mainDataType GetNextConnectedOper();
private:
    uniform_int_distribution<int>* connections_dist;
    static random_device rd;
    static mt19937 rnb;
};

RandomConnectionsProvider::RandomConnectionsProvider(mainDataType operatorsCount)
{
    uniform_int_distribution<int> op_dist(1, OperatorsCount);
    connections_dist = &op_dist;
}

mainDataType  RandomConnectionsProvider::GetNextConnectedOper()
{
    return *connections_dist(rnb);//Triing  to dereference as i remember it but got error there
}

最佳答案

您使 connections_dist 指向构造函数中的局部变量。当构造函数返回时,这个局部变量将被销毁,因此指针将不再指向有效的对象。

相反,我建议你跳过指针的使用,而是做这样的事情:

class RandomConnectionsProvider : RandomProviderBase
{
    std::uniform_int_distribution<int> connections_dist;  // Note: no pointer

    // ...

public:
    RandomConnectionsProvider::RandomConnectionsProvider(mainDataType operatorsCount)
        : connections_dist(1, operatorsCount)
    { }

    // ...
};

构造函数中冒号后面的部分称为初始化列表,用于初始化对象中的成员变量。

不使用指针也可以帮助您修复其他错误,因为您不需要使用解除引用。顺便说一句,该错误是因为函数调用具有更高的 operator precedence比取消引用运算符(因此编译器认为您正在执行 *(connections_dist(rnb)))。

关于c++ - 如何使用 uniform_int_distribution 作为构造函数中的类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19136013/

相关文章:

C++ 通用引用。为什么右值引用变成左值?

c++ - 如何在 SDL2 中旋转一个矩形?

powershell - 如何在命名空间中组织类?

android - 使用 fragment 时应用程序崩溃

c++ - 链接错误 : undefined reference within the same class

c++ - 通过 SWIG 从 C++ 调用 Go 回调函数

c++ - 通过窗口句柄连接的渲染和窗口系统的独立性

c++ - 在另一个线程上向 QObject 发出信号的正确方法?

python - python类中的init__和__init__有什么区别?

java - 对象的原始成员是在堆上还是在栈上?