基类指针调用派生类函数_C++ 多态性:虚函数--基类与派生类类型转换(第7章 05)例子问题解析(学习笔记:第8章 05)...
生活随笔
收集整理的這篇文章主要介紹了
基类指针调用派生类函数_C++ 多态性:虚函数--基类与派生类类型转换(第7章 05)例子问题解析(学习笔记:第8章 05)...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
虛函數[1]
問題:還記得第7章的例子嗎[2]?
例7-3 類型轉換規則舉例
#include <iostream> using namespace std; class Base1 { //基類Base1定義 public:void display() const {cout << "Base1::display()" << endl;} }; class Base2 : public Base1 { //公有派生類Base2定義 public:void display() const {cout << "Base2::display()" << endl;} }; class Derived : public Base2 { //公有派生類Derived定義 public:void display() const {cout << "Derived::display()" << endl;} };void fun(Base1 *ptr) { //參數為指向基類對象的指針ptr->display(); //"對象指針->成員名" } int main() { //主函數Base1 base1; //聲明Base1類對象Base2 base2; //聲明Base2類對象Derived derived; //聲明Derived類對象fun(&base1); //用Base1對象的指針調用fun函數fun(&base2); //用Base2對象的指針調用fun函數fun(&derived); //用Derived對象的指針調用fun函數return 0; }程序運行結果:
對程序的一些說明:
程序的本意時希望能夠寫一個通用的顯示函數fun(),根據需要指向不同的派生對象,然后調用各自display函數。但是沒有達到這個期望的效果。運行結果都是調用Base1的display函數。所以建議不要重新定義繼承而來的非虛函數。
- 為什么程序沒有達到期望效果?
在編譯階段,編譯器根據指針無法去判斷在運行時它會指向一個什么類型的對象。
- 用虛函數能解決上述問題的原理:
在編譯階段沒法正確地決定,就推遲這個決定,留到運行時在確定。程序運行時就能夠知道指針在某個時刻指向的實際對象。
- 怎么實現上述原理:
添加一個virtual關鍵字即可。它的意思是指示編譯器不要在編譯階段做靜態綁定,要為運行階段做動態綁定做好準備。
注意:加了virtual的虛函數都要在類外去實現函數體,不能寫成內聯函數(因為內聯函數是靜態綁定的)。
例8-4通過虛函數實現運行時多態
現在我們來改進一下第7章的程序:同原型的函數在類外寫成虛函數。
#include <iostream> using namespace std;class Base1 { public:virtual void display() const; //虛函數 }; void Base1::display() const {cout << "Base1::display()" << endl; }class Base2 : public Base1 { public:virtual void display() const; }; void Base2::display() const {cout << "Base2::display()" << endl; } class Derived : public Base2 { public:virtual void display() const; }; void Derived::display() const {cout << "Derived::display()" << endl; }void fun(Base1 *ptr) {ptr->display(); }int main() {Base1 base1;Base2 base2;Derived derived;fun(&base1);fun(&base2);fun(&derived);return 0; }程序運行結果:
參考
總結
以上是生活随笔為你收集整理的基类指针调用派生类函数_C++ 多态性:虚函数--基类与派生类类型转换(第7章 05)例子问题解析(学习笔记:第8章 05)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用python给女朋友惊喜100天快乐_
- 下一篇: 编译QT出错 Basic XLib fu