在这里,我们将讨论C ++中的统一初始化。从C ++ 11版本开始支持。统一初始化是一项功能,它允许使用一致的语法来初始化从原始类型到集合的变量和对象。换句话说,它引入了花括号初始化,该花括号初始化应用花括号({})来封装初始化程序值。
type var_name{argument_1, argument_2, .... argument_n}
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; int main() { int* pointer = new int[5]{ 10, 20, 30, 40, 50 }; cout<lt;"The contents of array are: "; for (int i = 0; i < 5; i++) cout << pointer[i] << " " ; }
The contents of array are: 10 20 30 40 50
#include <iostream> using namespace std; class MyClass { int arr[3]; public: MyClass(int p, int q, int r) : arr{ p, q, r } {}; void display(){ cout <<"The contents are: "; for (int c = 0; c < 3; c++) cout << *(arr + c) << ", "; } }; int main() { MyClass ob(40, 50, 60); ob.display(); }
The contents are: 40, 50, 60,
#include <iostream> using namespace std; class MyClass { int p, q; public: MyClass(int i, int j) : p(i), q(j) { } void display() { cout << "(" <<p <<", "<< q << ")"; } }; MyClass func(int p, int q) { return { p, q }; } int main() { MyClass ob = func(40, 50); ob.display(); }
(40, 50)
#include <iostream> using namespace std; class MyClass { int p, q; public: MyClass(int i, int j) : p(i), q(j) { } void display() { cout << "(" <<p <<", "<< q << ")"; } }; void func(MyClass p) { p.display(); } int main() { func({ 40, 50 }); }
(40, 50)