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

Forward Declarations ใน C++ คืออะไร


Forward declaration บอกคอมไพเลอร์ล่วงหน้าว่ามีคลาสชื่อนี้อยู่ (จะนิยามภายหลัง) ช่วยให้โค้ดหลัง declaration ใช้ชื่อคลาสได้ แม้ยังไม่เห็น definition

ตัวอย่าง

class Person;  // Forward declaration

void myFunc(Person p1) {
    // ใช้ Person ได้แล้ว แม้ยังไม่เห็น definition
}

class Person {  // Definition จริง
    // class definition here
};

ใช้เมื่อ: ต้องการใช้คลาสก่อนที่จะนิยามมัน (เช่น circular dependency, ลด header dependencies, pimpl idiom)