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)

更新於: 2020 年 8 月 27 日

1K+ 瀏覽

開啟你的 職業道路

完成課程獲得認證

開始
廣告