C++ 的统一初始化
这里我们将讨论 C++ 中的统一初始化。它从 C++11 版本开始得到支持。统一初始化是一种特性, 它允许使用一致的语法来初始化类型从基本类型到聚合的变量和对象。换句话说,它引入了大括号初始化,将大括号 ( {} ) 用于括起初始化值。
语法
type var_name{argument_1, argument_2, .... argument_n}初始化动态分配的数组
示例 (C++)
让我们看看下面的实现以得到更好的理解 −
#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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP