一、前言
C++的學習中,我想每個人都被變量定義和申明折磨過,比如我在大學筆試過的幾家公司,都考察了const和變量,類型的不同排列組合,讓你區別有啥不同。反正在學習C++過程中已經被折磨慣了,今天再來看看重溫下那段“輝煌的歷史”。先來看一段代碼:
Player pa; // (a) Player pb(); // (b) Player pc = Player(); // (c) Player pd(Player()); // (d) pd = Player() // (e)
#includestruct Player{ int id; const char* name; }; int main() { Player player = {10001, "c++"}; printf("%d, %s\n", player.id, player.name); }
1、系統內置類型
int ia{1}; // (a) int ib = {1}; // (b) int ic(1); // (c) int id = 1; // (d)很明顯,還是d 更符合習慣。
std::vectorva{1, 2, 3}; // (a) std::vector vb = {1, 2, 3}; // (b) std::vector vc(1, 10); // (c) std::vector vd{1, 10}; // (d)
std::pairgetPlayer() { return {10001, "c++"}; } std::map players = {{10001, "c++"}, {10002, "java”}};
Player pa{}; // (a) Player pb; // (b) Player pc(); // (c) Player pd(b); // (d) Player pe = b; // (e) Player pf = {b}; // (f)
class MyClass{ public: MyClass(int a):a_(a){ std::cout << "normal initializer list\n"; } MyClass(std::initializer_lista):b_(a) { std::cout << "initializer list constructor\n"; } MyClass(MyClass& my) { std::cout << "copy constructor\n"; this->a_ = my.a_; this->b_ = my.b_; } MyClass& operator=(MyClass& my) { std::cout << "operator = constructor\n"; this->a_ = my.a_; this->b_ = my.b_; return *this; } private: int a_; std::initializer_list b_; };
MyClass ma{1}; // (a) MyClass mb = {1, 2, 3}; // (b) MyClass mc(2); // (c) MyClass md = b; // (d) MyClass me(c); // (e) MyClass mf{e}; // (f) auto l{2, 2, 3,3}; MyClass mh{l}; // (e) ma = mb; // (h)
initializer list constructor
initializer list constructor
normal constructor list
copy constructor
copy constructor
copy constructor
initializer list constructor
operator = constructor