vendredi 11 septembre 2020

how to pass the reference of the class "Randomer" without constructor to a class via constructor, how does the class Randomer work?

i'm trying to store the reference of the class "Randomer" initiated in "main" to another class.
what would be best approach, the pointer or reference?

how does the class "Randomer" takes is initial values.

how does this work? operator()()

size_t operator()() {
        return dist_(gen_);
    }

Randomer taken from: [https://www.mmbyte.com/][1]

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /*  ... some convenient ctors ... */

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

someClass{
protected:
Randomer& random;

public:
     someClass(){
     this->random = ....; // <----------------------
     this->random{0, 9};  // this doesn't work.
}

     someClass(Randomer& random){
     this->random = random; // <----------------------
}

}

int main()
{
    Randomer randomer{0, 9}; // how does this work?
    someClass* test =  new someClass(randomer);
    int randomNumber = randomer(); // // how does this work?
    std::cout << "randomNumber" << randomNumber << endl;
    return 0;
}

result in error:

error: constructor for 'someClass' must explicitly initialize the member 'random' which does not have a default constructor

the error applies to default constructor as the overloaded constructor [1]: https://www.mmbyte.com/article/68666.html




Aucun commentaire:

Enregistrer un commentaire