2017-03-01 85 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

对不起,因为我的错误。我是更新问题 –