簡體   English   中英

C++ 如何使用初始化/構造函數創建新的 object?

[英]How does the C++ create new object with initialize/ constructor?

我試圖了解對象如何創建和初始化構造函數。 我想創建一個 object 和一個帶有“*name”功能的“person class”,並在我創建 object 后測試名稱指針是否為 NULL。

我首先使用動態分配“new”進行測試,以創建 object,指針為 null。 但是,如果我使用 static 創建 object 並且指針不是 null。

class person{
public:
    string *name;
person(){
}
~person(){}
};

以上是class的定義。

int main(){

person *jack = new person();
cout << jack->name << endl;
if(jack->name == NULL){
    cout << "is null" << endl;
} else{
    cout << "not null" << endl;
}
return 0;
}

上面會 output: 0x0, 就是 null

int main(){
person louis = person();
cout << louis.name << endl;

if(louis.name == NULL){
    cout << "is null" << endl;
} else{
    cout << "not null" << endl;
}
return 0;
}

上面會 output: 0x7ffeee80b918,不是 null

此外,如果我將兩者放在一起:

int main(){

person *jack = new person();
cout << jack->name << endl;
if(jack->name == NULL){
    cout << "is null" << endl;
} else{
    cout << "not null" << endl;
}
person louis = person();
cout << louis.name << endl;
if(louis.name == NULL){
    cout << "is null" << endl;
} else{
    cout << "not null" << endl;
}

return 0;
}

上面會 output: 0x0, 就是 null, 0x0, 就是 null。

我試圖弄清楚為什么使用“新”或不使用“名稱”指針會有不同的結果?

使用“new”,名稱指針將是 NULL 沒有“new”,名稱指針將不是 NULL

此外,如果我創建兩個對象,第一個使用 new 創建,第二個創建沒有 new。 結果將全部變為 NULL。 為什么第一個 object 會影響第二個 object 上的名稱指針?

您正在處理“未定義的行為”。 因此,不要嘗試區分兩種初始化類型的 output,而是將 class 定義中的名稱聲明從string *name; string *name = nullptr; 保證名稱以 NULL 開頭

暫無
暫無

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

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