更新问题: 为什么我们有“我正在构建”。 而我可以在那里倾斜?我在大学读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非常感谢您。
什么让您感到困惑?在这里调用构造函数:'President(“Franklin Delano Roosevelt”,“the USA”,1936)' –
当你创建一个类的*对象*,*实例*时,该对象被构造*并且适当的正在调用构造函数。 –
你从cppreference中得到了你的例子。 cplusplus.com/reference和cppreference.com是两个不同的竞争在线C++参考文献 – Cubbi