构造函数使用{a,b,c}作为参数,或者{a,b,c}实际在做什么? [英] Constructor using {a,b,c} as argument or what is {a,b,c} actually doing?
本文介绍了构造函数使用{a,b,c}作为参数,或者{a,b,c}实际在做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道,我可以像这样初始化数据。
I know, that I can initialize data like this.
int array[3] = { 1, 2, 3 };
甚至
int array[2][2] = { {1, 2}, {3, 4} };
我也可以使用 std :: vector
std::vector<int> A = { 1, 2, 3 };
假设我要编写自己的课程:
Let's say I want to write my own class:
class my_class
{
std::vector< int > A;
public:
//pseudo code
my_class(*x) { store x in A;} //with x={ {1, 2}, {3, 4} }
// do something
};
是否可以编写这样的构造函数,怎么可能?
Is it possible to write such a constructor and how is it possible? What is this statement
{{1,2},{3,4}}
到底在做什么?
我总是发现,您可以用这种方式初始化数据,但永远不会精确地执行它。
I always just find, that you can initialize data in this way, but never what it is doing precisely.
推荐答案
它称为 列表初始化 ,您需要一个 std :: initilizer_list 构造函数,可以在您的 my_class
中实现。
请参见(实时演示 )
See (Live Demo)
#include <iostream>
#include <vector>
#include <initializer_list> // std::initializer_list
class my_class
{
std::vector<int> A;
public:
// std::initilizer_list constructor
my_class(const std::initializer_list<int> v) : A(v) {}
friend std::ostream& operator<<(std::ostream& out, const my_class& obj) /* noexcept */;
};
std::ostream& operator<<(std::ostream& out, const my_class& obj) /* noexcept */
{
for(const int it: obj.A) out << it << " ";
return out;
}
int main()
{
my_class obj = {1,2,3,4}; // now possible
std::cout << obj << std::endl;
return 0;
}
这篇关于构造函数使用{a,b,c}作为参数,或者{a,b,c}实际在做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文