ในที่นี้เราจะพูดถึงการเริ่มต้นแบบสม่ำเสมอใน 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)