标签:google 前言 strong 学习 使用 历史 iostream pos 结构
Player pa; // (a) Player pb(); // (b) Player pc = Player(); // (c) Player pd(Player()); // (d) pd = Player() // (e)
对于c以为是调用了operator= 赋值运算吧?全然不是。而是先生成一个对象。然后调用Player的拷贝构造函数,生成对象pc。d和c是一样的。e才是真正调用赋值操作。是不是已经被这各式各样的对象申明搞的晕头专向了。如今C++11初始化列表正式登场。
#include <iostream> struct Player{ int id; const char* name; }; int main() { Player player = {10001, "c++"}; printf("%d, %s\n", player.id, player.name); }
C++11引入了初始化列表来初始化变量和对象。
1、系统内置类型
int ia{1}; // (a) int ib = {1}; // (b) int ic(1); // (c) int id = 1; // (d)非常明显。还是d 更符合习惯。
std::vector<int> va{1, 2, 3}; // (a) std::vector<int> vb = {1, 2, 3}; // (b) std::vector<int> vc(1, 10); // (c) std::vector<int> vd{1, 10}; // (d)
std::pair<int, const char*> getPlayer() { return {10001, "c++"}; } std::map<int, const char*> 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_list<int> a):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<int> 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
标签:google 前言 strong 学习 使用 历史 iostream pos 结构
原文地址:http://www.cnblogs.com/zhchoutai/p/7226928.html