簡體   English   中英

初始化類的非靜態成員變量在哪里?

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

初始化類的非靜態成員變量在哪里?

在類聲明內或構造函數內? 謝謝

在構造函數中。 構造函數用於初始化類的非靜態成員。


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

所以,在相應的源文件中這樣做 -

int foo::num = 10 ;

它在構造函數的初始化列表中。 如果使用編譯器生成的構造函數,那么原理是相同的,它只是隱式生成的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM