ตัวชี้ C++
การสร้างตัวชี้
คุณได้เรียนรู้จากบทที่แล้วว่าเราสามารถรับที่อยู่หน่วยความจำของตัวแปรได้โดยใช้ตัว&
ดำเนินการ:
ตัวอย่าง
string food = "Pizza";
// A food variable of type string
cout <<
food; // Outputs the value of food (Pizza)
cout << &food; // Outputs the memory address of food (0x6dfed4)
อย่างไรก็ตาม ตัวชี้เป็นตัวแปรที่เก็บที่อยู่หน่วยความจำเป็นค่าของมัน
ตัวแปรตัวชี้ชี้ไปที่ชนิดข้อมูล (เช่นint
หรือstring
) ที่เป็นประเภทเดียวกัน และสร้างขึ้นด้วยตัว*
ดำเนินการ ที่อยู่ของตัวแปรที่คุณกำลังใช้งานถูกกำหนดให้กับตัวชี้:
ตัวอย่าง
string food = "Pizza"; // A food variable
of type string
string* ptr =
&food; // A pointer variable, with the name
ptr, that stores the
address of food
// Output the value of food (Pizza)
cout << food << "\n";
// Output
the memory address of food (0x6dfed4)
cout << &food << "\n";
//
Output the memory address of food with the pointer (0x6dfed4)
cout <<
ptr << "\n";
ตัวอย่างอธิบาย
สร้างตัวแปรพอยน์เตอร์ชื่อptr
ที่ชี้ไปที่string
ตัวแปรโดยใช้เครื่องหมายดอกจัน
*
( string* ptr
) โปรดทราบว่าประเภทของตัวชี้จะต้องตรงกับประเภทของตัวแปรที่คุณใช้งานอยู่
ใช้ตัว&
ดำเนินการเพื่อจัดเก็บที่อยู่หน่วยความจำของตัวแปรที่เรียกว่าfood
และกำหนดให้กับตัวชี้
ตอนนี้ptr
เก็บค่าของfood
ที่อยู่หน่วยความจำ
เคล็ดลับ:มีสามวิธีในการประกาศตัวแปรพอยน์เตอร์ แต่ควรใช้วิธีแรก:
string* mystring; // Preferred
string *mystring;
string * mystring;