虛函數與動態綁定

#include <iostream>

using namespace std;

class A{
public:
 A(){
  cout<<"A constructor"<<endl;
  f();//構造函數中對虛函數的調用採用靜態綁定!(反證法!)
 }

 ~A(){
  cout<<"A destructor"<<endl;
 }

 virtual void  f(){
  cout<<"This is A::f()"<<endl;
 }

 void g(){
  cout<<"This is A::g()"<<endl;
 };

};

class B: public A{
public:
 B(){
  cout<<"B Constructor"<<endl;
 }
 ~B(){
  cout<<"B destructor"<<endl;
 }

 void g(){
  cout<<"This is B::g()"<<endl;
 }

 void f(){
  cout<<"This is B::f()"<<endl;
 }
 
 //派生類新增成員函數
 void h(){
  f();
  g();
 }
};

int main(){

B b;
A *p = &b;
p->f();
p->A::f();//通過類名受限來訪問虛函數時不需要動態綁定
p->g();

//((B*)p)->h();//這種強制轉換手段不安全,可能導致不屬於A類的內存空間被修改
//基類指針訪問派生類新增成員函數時要用到dynamic_cast(類型轉換操作)
B *q;
q = dynamic_cast<B*>(p);
if(q!=NULL)//q有可能爲空
 q->h();

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章