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

ความแตกต่างระหว่าง definition และ declaration ใน C++

ใน C++ declaration และ definition สับสนกันบ่อย Declaration หมายถึง (ใน C) ว่าคุณบอกคอมไพเลอร์เกี่ยวกับ type, size และในกรณี function declaration คือ type และ size ของพารามิเตอร์ของตัวแปร, user-defined type, หรือฟังก์ชันในโปรแกรมของคุณ ไม่มีพื้นที่หน่วยความจำถูกจองสำหรับตัวแปรในกรณี declaration

Definition หมายถึง นอกจากสิ่งที่ declaration ทำแล้ว ยังจองพื้นที่ในหน่วยความจำเพิ่มเติม คุณพูดได้ว่า "DEFINITION = DECLARATION + SPACE RESERVATION"

ตัวอย่าง declarations -

extern int a; // ประกาศตัวแปร a โดยไม่ define
struct _tagExample { int a; int b; }; // ประกาศ struct
int myFunc (int a, int b); // ประกาศฟังก์ชัน

ตัวอย่าง definitions -

int a;
int b = 0;
int myFunc (int a, int b) { return a + b; }
struct _tagExample example;