C++11 通用初始化方法

在阅读EOS源码时,发现一种比较怪异的初始化语法,后来发现是C++11 新增的通用初始化语法,使用{}而不是()来调用构造函数:

chain::action create_newaccount(const name& creator, const name& newaccount, public_key_type owner, public_key_type active) {
	//初始化列表构造函数
   return action {
      tx_permission.empty() ? vector<chain::permission_level>{{creator,config::active_name}} : get_account_permissions(tx_permission),
      eosio::chain::newaccount{
         .creator      = creator,
         .name         = newaccount,
         .owner        = eosio::chain::authority{1, {{owner, 1}}, {}},
         .active       = eosio::chain::authority{1, {{active, 1}}, {}}
      }
   };
}

例子:

#include <iostream>
using namespace std;
 class Test{
 public:

 	Test(int a,int b)
 	{
 		cout<<"Test 1"<<endl;
 	}

	Test(int a,int b,int c)
 	{
 		cout<<"Test 2"<<endl;
 	}
 };
 int main()
 {
 	Test{1,2};
 	Test{1,2,3};
 	return 0;
 }

输出:

[root@localhost c++11]# ./initial_list
Test 1
Test 2

参考:

https://www.cnblogs.com/Braveliu/p/6224105.html


猜你喜欢

转载自blog.csdn.net/idwtwt/article/details/80754715