虚函数的提出其实和C++的多态有着莫大的关系,先看一个例子;
#include <iostream>
using namespace std;
class A
{
public:
void print()
//virtual void print()
{
cout<<"This is A"<<endl;
}
};
class B:public A
{
public:
void print(){cout<<"This is B"<<endl;}
};
int main(){
A a;
B b;
a.print();
b.print();
A* p1=&a;
A* p2=&b;
p1->print();
p2->print();
}
|
从结果可以看到:
This is A
This is B
This is A
This is A
将父类的print函数改为虚函数,也是将
void print()改为virtual void print(),则结果就不同了:
This is A
This is B
This is A
This is B
阅读(920) | 评论(0) | 转发(0) |