Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Uniform Initialization ใน C++ (C++11)


Uniform Initialization เป็นฟีเจอร์ตั้งแต่ C++11 ที่อนุญาตให้ใช้ syntax เดียวกัน (brace-initialization {}) ในการ initialize ตัวแปรและอ็อบเจ็กต์ทุกประเภท ตั้งแต่ primitive types ไปจนถึง aggregates และ classes

Syntax

type var_name{argument_1, argument_2, ..., argument_n}

1. Initialize Dynamically Allocated Arrays

#include <bits/stdc++.h>
using namespace std;

int main() {
    int* pointer = new int[5]{ 10, 20, 30, 40, 50 };
    cout << "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

2. Initialization ของ Array Data Member ใน Class

#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,

3. Implicitly Initialize Objects เพื่อ Return

#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 }; // uniform initialization
}

int main() {
    MyClass ob = func(40, 50);
    ob.display();
}

เอาต์พุท

(40, 50)

4. Implicitly Initialize Function Parameter

#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 }); // ส่ง argument ด้วย brace-init
}

เอาต์พุท

(40, 50)

ข้อดีของ Uniform Initialization

  • Syntax สม่ำเสมอ ลดความสับสน
  • ป้องกัน narrowing conversions (เตือน error ถ้าเสีย precision)
  • ใช้ได้กับทุกประเภท: primitive, array, struct, class, STL containers