-1
class A{
        int a;
    public:
        A(int inA = 0);
        int getA;
    protected:
        void setA(int inA);
    };
A::A(int inA)
    {
        setA(inA)
    }
void A::setA(int inA){
        //need to set a as static random number
        a = inA;
    }
int A::getA()const
    {
        return a;
    }

How could I possibly generate a random using a static member for a? I have seen something like this online: Random Number In-Class Initialisation but not really sure how to use it.

Community
  • 1
  • 1

1 Answers1

1

The simplest way is probably to make global instances of the PRNG classes.

std::uniform_int_distribution<int> dist;
std::mt19937 rng((std::random_device()()));

struct foo
{
    static int bar;
};

int foo::bar = dist(rng);

Of course, put the global objects and initialization in a .cpp file (thanks @AnonMail!).

Using the old (bad) random number facilities, you could use:

int foo::bar = (srand(time(0)), rand());

This is also not great because you've secretly seeded srand which is sort of weird, and rand is bad.

The (arguably) fun way is to do this:

int foo::bar = []() {std::uniform_int_distribution<int> dist; std::mt19937 mt((std::random_device()())); return dist(mt); }();

You use a lambda to create the variables and return the value, eliminating extra objects and putting it all on one line.

I realized I don't think I've seen a lambda used like this before, so I wasn't sure if it would work. My compiler seems fine with it, and it runs as intended, so my assumption would be this is correct.

Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36