Correct place to initialize class variables?

前端 未结 5 1909
盖世英雄少女心
盖世英雄少女心 2021-01-31 04:28

Where is the correct place to initialize a class data member? I have the class declaration in a header file like this:

Foo.h:

class Foo {
private:
    in         


        
5条回答
  •  孤独总比滥情好
    2021-01-31 04:57

    To extend on Jared's answer, if you want to initialize it the way it is now, you need to put it in the Constructor.

    class Foo
    {
    public:
        Foo(void) :
        myInt(1) // directly construct myInt with 1.
        {
        }
    
        // works but not preferred:
        /*
        Foo(void)
        {
            myInt = 1; // not preferred because myInt is default constructed then assigned
                       // but with POD types this makes little difference. for consistency
                       // however, it's best to put it in the initializer list, as above
                       // Edit, from comment: Also, for const variables and references,
                       // they must be directly constructed with a valid value, so they
                       // must be put in the initializer list.
        }
        */
    
    private:
        int myInt;
    };
    

提交回复
热议问题