我希望我自己的类可以像vector一样进行列表初始化:
myClass a = {1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
我怎么能用C++ 11功能呢?
C++ 11有一个初始化列表的概念.要使用它,请添加一个接受单个类型参数的构造函数std::initializer_list<T>.例:
#include <vector>
#include <initializer_list>
#include <iostream>
struct S
{
std::vector<int> v_;
S(std::initializer_list<int> l)
: v_(l)
{
std::cout << "constructed with initializer list of length " << l.size();
}
};
int main()
{
S s = { 1, 2, 3 };
return 0;
}
Run Code Online (Sandbox Code Playgroud)