关于C#:类的非静态成员变量在哪里初始化? | 珊瑚贝

where are the non-static member variables of a class initialized?


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

在类声明中还是在构造函数中??谢谢


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

1
2
3
4
5
class foo
{
    static int num; // static variable don’t belong to any particular instance of a class.
    foo(){}
};

所以,在对应的源文件中这样操作-

1
int foo::num = 10 ;

它在构造函数的初始化列表中。如果使用编译器生成的构造函数,那么原理是一样的,只是隐式生成。


最好在构造函数初始化列表中:
http://www.parashift.com/c -faq-lite/ctors.html#faq-10.6


来源:https://www.codenong.com/5295078/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?