ตัว สร้าง C++
ตัวสร้าง
คอนสตรัคเตอร์ใน C ++ เป็นวิธีการพิเศษที่จะถูกเรียกโดยอัตโนมัติเมื่อมีการสร้างอ็อบเจกต์ของคลาส
ในการสร้าง Constructor ให้ใช้ชื่อเดียวกับ class ตามด้วยวงเล็บ()
:
ตัวอย่าง
class MyClass { // The class
public:
// Access specifier
MyClass() {
// Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call
the constructor)
return 0;
}
หมายเหตุ:คอนสตรัคเตอร์มีชื่อเดียวกับคลาส เป็น always public
และไม่มีค่าส่งคืน
พารามิเตอร์ตัวสร้าง
ตัวสร้างยังสามารถรับพารามิเตอร์ (เช่นเดียวกับฟังก์ชันปกติ) ซึ่งอาจเป็นประโยชน์สำหรับการตั้งค่าเริ่มต้นสำหรับแอตทริบิวต์
คลาสต่อไปนี้มีbrand
และmodel
คุณลักษณะyear
และตัวสร้างที่มีพารามิเตอร์ต่างกัน ภายใน Constructor เราตั้งค่าแอตทริบิวต์เท่ากับพารามิเตอร์ Constructor ( brand=x
, ฯลฯ ) เมื่อเราเรียก Constructor (โดยการสร้างวัตถุของคลาส) เราส่งพารามิเตอร์ไปยัง Constructor ซึ่งจะตั้งค่าของแอตทริบิวต์ที่เกี่ยวข้องให้เหมือนกัน:
ตัวอย่าง
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z)
{ // Constructor with parameters
brand =
x;
model = y;
year = z;
}
};
int main() {
//
Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang",
1969);
// Print values
cout << carObj1.brand << " "
<< carObj1.model << " " << carObj1.year << "\n";
cout <<
carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
คอนสตรัคเตอร์ยังสามารถกำหนดนอกคลาสได้เช่นเดียวกับฟังก์ชัน ขั้นแรก ประกาศตัวสร้างภายในคลาส แล้วกำหนดภายนอกคลาสโดยระบุชื่อของคลาส ตามด้วยตัว::
ดำเนินการแก้ไขขอบเขต ตามด้วยชื่อของตัวสร้าง (ซึ่งเหมือนกับคลาส):
ตัวอย่าง
class Car { // The class
public: // Access
specifier
string brand; // Attribute
string model; // Attribute
int year;
// Attribute
Car(string x, string y, int z); //
Constructor declaration
};
// Constructor definition outside the
class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create
Car objects and call the constructor with different values
Car
carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " <<
carObj1.model << " " << carObj1.year << "\n";
cout <<
carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}