Correct place to initialize class variables?

前端 未结 5 1963
盖世英雄少女心
盖世英雄少女心 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 05:03

    What you have there is an instance variable. Each instance of the class gets its own copy of myInt. The place to initialize those is in a constructor:

    class Foo {
    private:
        int myInt;
    public:
        Foo() : myInt(1) {}
    };
    

    A class variable is one where there is only one copy that is shared by every instance of the class. Those can be initialized as you tried. (See JaredPar's answer for the syntax)

    For integral values, you also have the option of initializing a static const right in the class definition:

    class Foo {
    private:
        static const int myInt = 1;
    };
    

    This is a single value shared by all instances of the class that cannot be changed.

提交回复
热议问题