沒有使用virtual的情況:
#include <iostream>
using namespace std;
class Parent {
public:
void show() {
cout << "I'm parent" << endl;
}
};
class child :public Parent {
public:
void show() {
cout << "I'm child" << endl;
}
};
int main() {
Parent *ptr = new child();
ptr->show();
system("pause");
return 0;
}
OutputParent
think different,change world
當(dāng)在base類中使用了virtual function時(shí)弛姜,我們就能訪問用base類對(duì)象的指針糜芳,訪問派生類的方法了飒货。看下面:
#include <iostream>
using namespace std;
class Parent {
public:
virtual void show() {
cout << "I'm parent" << endl;
}
};
class child :public Parent {
public:
void show() {
cout << "I'm child" << endl;
}
};
int main() {
Parent *parent_object_ptr = new child();
parent_object_ptr->show();
system("pause");
return 0;
}
virtual function