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

Constructor Delegation ใน C++

Constructor Delegation คืออะไร? เมื่อ constructor เรียก constructor อื่นของคลาสเดียวกัน เรียกว่า constructor delegation ฟีเจอร์นี้มีตั้งแต่ C++11

ลองดูโปรแกรมต่อไปนี้และวิเคราะห์ว่ามีปัญหาอะไร

ตัวอย่าง (ก่อนใช้ Delegation)

#include <iostream>
using namespace std;

class MyClass {
  int a, b, c;
public:
  MyClass() {
    a = b = c = 0;
  }
  MyClass(int c) {
    // การเริ่มต้น a และ b ซ้ำซ้อน ต้องการแค่เริ่มต้น c
    a = 0;
    b = 0;
    this->c = c;
  }
  void display() {
    cout << "a : " << a << ", b : " << b << ", c : " << c;
  }
};

main() {
  MyClass my_obj(5);
  my_obj.display();
}

ผลลัพธ์

a : 0, b : 0, c : 5

โค้ดทำงานได้ แต่มีโค้ดซ้ำ Constructor แรกตั้งค่า a และ b เป็น 0 ได้ ดังนั้นถ้าใช้ constructor แรกใน constructor ที่สอง จะมีประสิทธิภาพมากขึ้น ใช้วิธี constructor delegation

ตัวอย่าง (ใช้ Delegation)

#include <iostream>
using namespace std;

class MyClass {
  int a, b, c;
public:
  MyClass() {
    a = b = c = 0;
  }
  MyClass(int c) : MyClass() { // ใช้ constructor delegation
    this->c = c;
  }
  void display() {
    cout << "a : " << a << ", b : " << b << ", c : " << c;
  }
};

main() {
  MyClass my_obj(5);
  my_obj.display();
}

ผลลัพธ์

a : 0, b : 0, c : 5