ในส่วนนี้ เราจะพูดถึงข้อเท็จจริงที่น่าสนใจที่จำกัดการเข้าถึงเมธอดคลาสที่ได้รับใน C++ เราจะดูตัวอย่างและวิเคราะห์ผลลัพธ์เพื่อทราบข้อมูลเพิ่มเติมเกี่ยวกับข้อจำกัดของการใช้เมธอดคลาสที่ได้รับใน C++
ตัวอย่าง (C++)
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <iostream>
using namespace std;
class BaseClass {
public:
virtual void display(){
cout << "Print function from the base class" << endl;
}
};
class DerivedClass: public BaseClass {
private:
void display() {
cout << "Print function from the derived class" << endl;
}
};
int main() {
} ไม่เป็นไร ตอนนี้ถ้าเราแทนที่บล็อกฟังก์ชันหลักด้วยสิ่งนี้ เราจะได้รับข้อผิดพลาดดังต่อไปนี้ −
int main() {
DerivedClass d;
d.display();
} ผลลัพธ์
main.cpp: In function ‘int main()’:
main.cpp:20:15: error: ‘virtual void DerivedClass::display()’ is private
within this context
d.display();
^
main.cpp:13:10: note: declared private here
void display() {
^~~~~~~ มันแสดงข้อผิดพลาดเนื่องจากวิธีการในคลาสที่ได้รับเป็นแบบส่วนตัว ทีนี้มาดูการใช้งานนี้ โดยที่ฟังก์ชันถูกเรียกโดยใช้ตัวชี้ฐาน เรียกฟังก์ชันนี้ก็ได้
ตัวอย่าง (C++)
#include <iostream>
using namespace std;
class BaseClass {
public:
virtual void display(){
cout << "Print function from the base class" << endl;
}
};
class DerivedClass: public BaseClass {
private:
void display() {
cout << "Print function from the derived class" << endl;
}
};
int main() {
BaseClass *b = new DerivedClass;
b->display();
} ผลลัพธ์
Print function from the derived class
จากโปรแกรมด้านบน เราจะเห็นว่ามีการเรียกฟังก์ชันส่วนตัว DerivedClass::display() ผ่านตัวชี้คลาสพื้นฐาน โปรแกรมทำงานได้ดีเนื่องจากฟังก์ชัน display() เป็นสาธารณะในคลาสพื้นฐาน ตัวระบุการเข้าถึงได้รับการตรวจสอบ ณ เวลารวบรวมและ display() เป็นสาธารณะในคลาสพื้นฐาน ระหว่างรันไทม์ จะเรียกเฉพาะฟังก์ชันที่สอดคล้องกับอ็อบเจ็กต์ปลายแหลมเท่านั้น และไม่ได้ตรวจสอบตัวระบุการเข้าถึง ดังนั้นฟังก์ชันส่วนตัวของคลาสที่ได้รับจึงถูกเรียกผ่านพอยน์เตอร์ของคลาสฐาน