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

Default Constructor ใน C++

Class constructor เป็น special member function ของคลาสที่ทำงานทุกครั้งที่เราสร้างอ็อบเจ็กต์ใหม่ของคลาสนั้น

Constructor จะมีชื่อตรงกับชื่อคลาส และไม่มี return type เลย ไม่ว่าจะเป็น void ก็ตาม Constructor มีประโยชน์มากสำหรับตั้งค่าเริ่มต้นให้ member variables

ตัวอย่างต่อไปนี้อธิบายแนวคิดของ constructor:

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

class Line {
public:
    void setLength(double len);
    double getLength(void);
    Line(); // นี่คือ constructor
private:
    double length;
};

// Member functions definitions รวมถึง constructor
Line::Line(void) {
    cout << "Object is being created" << endl;
}

void Line::setLength(double len) {
    length = len;
}

double Line::getLength(void) {
    return length;
}

// Main function
int main() {
    Line line;
    // ตั้งค่าความยาว
    line.setLength(6.0);
    cout << "Length of line: " << line.getLength() << endl;
    return 0;
}

ผลลัพธ์

Object is being created
Length of line: 6