A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface
//int * is the type of an array variable
int*my_int_array;//this is how you initialize an array
my_int_array=newint[10];//this is how you index into an array
intone_element=my_int_array[0];delete[]my_int_array;
delete 一般在类的析构函数中出现(需要手动掉释放这块内存)
这里那个虚函数等于 0 的意义在于,让继承它的类必须实现该函数,否则编译失败。这种虚函数叫作纯虚函数(pure virtual function
#include<vector>#include<cassert>#include<iostream>#include<string>structPresident{std::stringname;std::stringcountry;intyear;President(std::stringp_name,std::stringp_country,intp_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=(constPresident&other)=default;};intmain(){std::vector<President>elections;std::cout<<"emplace_back:\n";auto&ref=elections.emplace_back("Nelson Mandela","South Africa",1994);assert(ref.year==1994&&"uses a reference to the created object (C++17)");std::vector<President>reElections;std::cout<<"\npush_back:\n";reElections.push_back(President("Franklin Delano Roosevelt","the USA",1936));std::cout<<"\nContents:\n";for(Presidentconst&president:elections)std::cout<<president.name<<" was elected president of "<<president.country<<" in "<<president.year<<".\n";for(Presidentconst&president:reElections)std::cout<<president.name<<" was re-elected president of "<<president.country<<" in "<<president.year<<".\n";}