Initialization of object static members

前端 未结 7 1051
余生分开走
余生分开走 2021-01-24 21:51

Static members confuse me sometimes. I understand how to initialize a simple built in type such as int with something along the lines of int myClass::statVar

相关标签:
7条回答
  • 2021-01-24 22:17

    Just write a function which returns a reference to a properly randomized RandomGenerator and turn itsGenerator into a reference to a generator:

    class myClass
    {
    public:
     // Some methods...
    
    protected:
     // make this a reference to the real generator
     static RandomGenerator& itsGenerator;
    public:
     static RandomGenerator& make_a_generator() 
     {
       RandomGenerator *g=0;
        g=new RandomGenerator();
        g->Randomize();
       return *g;
     }
    }
    
    RandomGenerator& myClass::itsGenerator=myClass::make_a_generator();
    
    0 讨论(0)
  • 2021-01-24 22:18

    You could create wrapper class which will hold RandomGenerator instance in it and will call RandomGenerator::Randomize in its constructor.

    0 讨论(0)
  • 2021-01-24 22:20

    Is it only a one function that needs RandomGenerator? You may do this in this way:

    int myClass::foo() { static RandomGenerator itsGenerator = RandomGenerator::Randomize() ... }

    0 讨论(0)
  • 2021-01-24 22:33

    Put it in a private field, expose a static accessor. In the accessor, if the member is not yet initialized, initialize it.

    0 讨论(0)
  • 2021-01-24 22:33

    If only myClass needs the RandomGenerator, then:

    myClass::myClass()
    {
        itsGenerator.Randomize();
    }
    

    Does it matter if you re-randomize your random generator for each object? I'm assuming no ;-)

    0 讨论(0)
  • 2021-01-24 22:37

    If RandomGenerator is copyable, you can use a helper function for initialization:

    RandomGenerator init_rg() {
        RandomGenerator rg;
        rg.Randomize();
        return rg;
    }
    
    RandomGenerator myClass::itsGenerator = init_rg();
    
    0 讨论(0)
提交回复
热议问题