2017-03-01 68 views
-1

更新問題: 爲什麼我們有「我正在構建」。 而我可以在那裏傾斜?我在大學讀C++書,但我確實發現。構造函數的工作原理

我很抱歉,因爲一些錯誤。

#include <vector> 
#include <string> 
#include <iostream> 

struct President { 
    std::string name; 
    std::string country; 
    int year; 

    President(std::string p_name, std::string p_country, int p_year) 
     : name(std::move(p_name)) 
     , country(std::move(p_country)) 
     , year(p_year) 
    { 
     std::cout << "I am being constructed.\n"; 
    } 
    President(President&& other) 
     : name(std::move(other.name)) 
     , country(std::move(other.country)) 
     , year(other.year) 
    { 
     std::cout << "I am being moved.\n"; 
    } 
    President& operator=(const President& other) = default; 
}; 

int main() 
{ 
    std::vector<President> reElections; 
    std::cout << "\npush_back:\n"; 
    reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); 

    for (President const& president : reElections) { 
     std::cout << president.name << " was re-elected president of " 
        << president.country << " in " << president.year << ".\n"; 
    } 
} 

輸出:

的push_back: 我正在興建。 我正在感動。

\ n非常感謝您。

+0

什麼讓您感到困惑?在這裏調用構造函數:'President(「Franklin Delano Roosevelt」,「the USA」,1936)' –

+0

當你創建一個類的*對象*,*實例*時,該對象被構造*並且適當的正在調用構造函數。 –

+0

你從cppreference中得到了你的例子。 cplusplus.com/reference和cppreference.com是兩個不同的競爭在線C++參考文獻 – Cubbi

回答

1

創建類的實例會自動調用構造函數。在「總統」的程序構造,當你安放向量與元素「納爾遜·曼德拉,當回」富蘭克林·羅斯福」被調用。

+0

對不起,因爲我的錯誤。我是更新問題 –

1

這裏的例子可能是打算以表明std::vector::emplace_back結構到位,但push_back移動

我們可以看到使用(更詳細的)版本總統

struct President { 
    std::string name; 
    std::string country; 
    int year; 

    President(std::string p_name, std::string p_country, int p_year) 
     : name(std::move(p_name)) 
     , country(std::move(p_country)) 
     , year(p_year) 
    { 
     std::cout << "I am being constructed at " << this << ".\n"; 
    } 
    President(President&& other) 
     : name(std::move(other.name)) 
     , country(std::move(other.country)) 
     , year(other.year) 
    { 
     std::cout << "I am being moved from " << &other << " to " << this << ".\n"; 
    } 
    President(const President& other) 
     : name(other.name) 
     , country(other.country) 
     , year(other.year) 
    { 
     std::cout << "I am being copied from " << &other << " to " << this << ".\n"; 
    } 
    ~President() 
    { 
     std::cout << "I am being destructed at " << this << ".\n"; 
    } 
}; 

會發生什麼更詳細的輸出示例:

emplace_back: 
I am being constructed at 0x2b2b57e17c30. 

push_back: 
I am being constructed at 0x7ffcb9a0cec0. 
I am being moved from 0x7ffcb9a0cec0 to 0x2b2b57e17cb0. 
I am being destructed at 0x7ffcb9a0cec0. 

Contents: 
Nelson Mandela was elected president of South Africa in 1994. 
Franklin Delano Roosevelt was re-elected president of the USA in 1936. 
I am being destructed at 0x2b2b57e17cb0. 
I am being destructed at 0x2b2b57e17c30. 
+0

對不起,因爲我的錯誤。我是更新問題 –