samedi 9 décembre 2017

Default constructor setting random value

I'm writing a simple class for atoms objects. Here's what I've written so far:

#include <random>

class Atom {
    int mSpin;

public:
    Atom();
    Atom(int);
    Atom(const Atom&);
    ~Atom() {}

    Atom& operator= (const Atom &atom);
};

And the .cpp file:

include "Atom.h"

Atom::Atom() {
}
Atom::Atom(int spin) : mSpin(spin) {}
Atom::Atom(const Atom& copy) : mSpin(copy.mSpin) {}

/*  OPERATORS  */

Atom& Atom::operator= (const Atom &copy) {
    mSpin = copy.mSpin;
    return *this;
}

I want to make the default constructor such that when I'm creating an object, mSpin will be randomly set as 1 or -1. I understand how to do it with rand() but rand() is not very good and I'd like to use . I'm kind of confused by the use of , even after reading the documentation and other answers on here. Usually I'd do something like this:

#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0,1);
int random_number = dis(gen);

but I'm not sure how to use it inside a class. I tried placing it inside the default constructor but I think it's wrong because it would seed each time I create an atom?

Hope the question is clear.




Aucun commentaire:

Enregistrer un commentaire