簡體   English   中英

C++中不同的聲明方式有什么區別?

[英]What is the difference between the different declarations methods in C++?

以下聲明有什么區別?

C c1 {C(42)};       
C c2 (C(42));    
C c3 {7};   
C c4 = {7};   
C c5 (7);

其中 C 是:

struct C {
    int x;
    C(int n): x{n} {};
    C(const C &c) {x=c.x;};
};   

將調用哪個構造函數,或者是否會創建一些臨時的 object?

讓我們對您的結構做一個簡單的更改,以便它打印正在調用的構造函數:

struct C {
    int x;
    C(int n): x{n} { cout << "calling C(int n) \n"; };
    C(const C &c) { x=c.x; cout << "calling C(const C &c) \n"; };
};   
C c1 {C(42)};
C c2 (C(42)); 
C c3 {7};   
C c4 = {7};
C c5 (7);  

// output:
// calling C(int n)
// calling C(int n)
// calling C(int n)
// calling C(int n)
// calling C(int n)

C c6(c1); // this one uses the copy constructor

// output:
// calling C(const C &c)
C c1 {C(42)};
// not sure this works

C c2 (C(42));
// calls the constructor of C with 42 and then copies the object that temporary created to the c2 
// object b calling the copy constructor of C

C c3 {7};
// not sure this works

C c4 = {7};
// not sure this works
// it should be and array like :
// C c4[] = {C(7)} ;
// to create and array of objects with initialized values ( C ( 7 ) )

C c5 (7);
// will create c5 with initialized value x = 5

暫無
暫無

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

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