c 類的建構函式初始化問題??

時間 2021-06-26 05:53:24

1樓:Right

"If you don』t specify any constructors, the compiler will write one for you that doesn』t take any arguments. This compiler-generated default constructor calls the default constructor on all object members of the class, but does not initialize the language primitives such as int and double. Nonetheless, it allows you to create objects of that class.

However,if you declare a default constructor, or any other constructor, the compiler no longer generates a default constructorfor you."

-- from Professional C++, Second Edition

You declare a constructor:

kk(int id)

Sothere's no default constructor for initializing:

kk p; // This tries to invoke the 0-argument default constructor.

But you can write:

kk p(5);

"Aconstructor with defaults for all its parameters can function as a default constructor. That is, you can construct an object of that class without specifying any arguments. If you try to declare both a default constructor and a multi-argument constructor with defaults for all its parameters, the compiler will complain because it won』t know which constructor to call if you don』t specify any arguments.

"-- from Professional C++, Second Edition

So the 2nd one works.

C 建構函式 父類 成員物件的如何專業地初始化

已登出 不考慮效能的情況下 也有以下問題 1.要求這個成員的型別有可訪問的無參建構函式2.要求這個成員的型別有可訪問的賦值函式 很顯然很多態別並不符合這幾點 正確做法 class Person Person std string name name public void SetName std s...

類初始化時 this 指標何時生成,在建構函式中如何確保 this 指標有效?

靈劍 this就是個指標,當然不存在準備沒準備好的問題了,就算隱式使用欄位和方法也是相當於使用了指標啊 主要是這樣幾個問題 1.建構函式沒執行完的時候,不一定所有欄位都正確初始化了2.基類建構函式執行時,子類的虛函式表沒有初始化,此時呼叫虛函式不能進入子類實現,如果是純虛函式甚至會直接崩潰 你只儲存...

C 類本身的初始化和靜態欄位的初始化到底發生在什麼時候?

餘葉 其實就兩個構造器。乙個是靜態的,乙個是普通的。靜態構造器得需要你第一次訪問到該類的時候會被觸發。建立的時候,包括 static 成員變數的初始化和static構造器,其實 static 成員變數會整合進static構造器裡面的。而普通成員變數也會整合進普通構造器裡面的。 天煞 如 Sai說的,...