初始化类的非静态成员变量在哪里?

use*_*213 2 c++

初始化类的非静态成员变量在哪里?

在类声明内或构造函数内?谢谢

Mah*_*esh 5

在构造函数中.构造函数用于初始化类的非静态成员.


class foo
{
    static int num; // static variable don't belong to any particular instance of a class.
    foo(){}
};
Run Code Online (Sandbox Code Playgroud)

所以,在相应的源文件中这样做 -

int foo::num = 10 ;
Run Code Online (Sandbox Code Playgroud)