没有使用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;
}
think different,change world
当在base类中使用了virtual function时,我们就能访问用base类对象的指针,访问派生类的方法了。看下面:
#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;
}