簡體   English   中英

為什么 c++ 編譯器提供它自己的默認構造函數

[英]Why c++ compiler provide's it's own default constructor

My Question is when we create a object of any class in c++ then if we have not provided any type of constructor in our class then c++ compiler provides it's own default constructor. 那么為什么編譯器提供它自己的構造函數。 提前致謝。

我沒有查過任何關於此事的歷史,但這里有一些可能的原因:

如果未隱式定義默認構造函數,則以下內容將無法編譯:

struct X {
    std::string str;
};

//...

X x;

因為X沒有默認構造函數。 你需要寫

struct X {
    std::string str;

    X() : str() {}
};

//...

X x;

當很清楚其意圖時,這似乎不必要的麻煩。 與使用 arguments 進行初始化相比,這是一個語義清晰的常見用例。


Also, as long as the class is plain old data (POD), meaning that it is a class that would also be allowed as a C structure, then it was (and is) intended that C++ be (mostly) compatible with C. 以 C 為例

struct X {
    int i;
};

//...

struct X x;

是允許的,因此在 C++ 中也應該允許。 如果沒有默認初始化每個成員的默認構造函數,則需要對此類 class 和初始化有特殊規則,以便不需要調用構造函數,而只是讓成員具有不確定的值。 But the same rule should not be applied to class members which do have proper constructors, since it shouldn't be possible to leave a class type with class invariants in an indeterminate state.

暫無
暫無

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

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