c++ - 构造函数如何工作

标签 c++ constructor copy-constructor

<分区>

更新问题: 为什么我们有“我正在 build ”。 我在哪里可以依靠它? 我在大学读了 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";
    }
}

输出:

推回: 我正在 build 中。 我被感动了。

\n非常感谢。

最佳答案

创建类的实例会自动调用构造函数。在您的程序中,当您放置带有“Nelson Mandela”的 vector 元素,以及回“Franklin Roosevelt”时,将调用“President”的构造函数。

关于c++ - 构造函数如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42527329/

相关文章:

c++ - 删除复制构造函数和复制赋值运算符。其中哪些是必不可少的?

c++ - C++ 11统一初始化时出现“结构初始化程序中的过多元素”错误

c++ - Wind River Workbench 3.3 中具有数据类型的枚举

c++ - 从另一个模型中提取子模型?

c++ - Mingw 和 Eclipse 无法找到库

c++ - 如果参数中没有传递任何值,如何创建具有默认值的对象?

c++ - 通过指针用自定义类填充 vector - 构造函数有问题

c++ - 在 C++ 中,所有容器类型的 std::end 是否保证为 O(1)?

c++ - 队列段错误的复制构造函数

c++ - 在 C++ 中将一个类对象分配给另一个类对象