虚函数与动态联编的内容(多态)
虚函数的作用
在类的继承当中,往往会存在派生类中的函数需要重新定义的现象,但是重新定义之后的函数可能发挥不了我们所希望的后果,例如:
#include <iostream>
using namespace std;
class shape{
public:
void draw(){cout<<"I am shape"<<endl;}
void fun(){draw();}
};
class circle:public shape{
public:
void draw(){cout<<"I am circle"<<endl;}
};
void main(){
circle oneshape;
oneshape.fun();
}
输出结果为:I am shape。
并没有调用更改后的draw()函数,为了解决这个问题,我们引入了virtual虚函数来解决问题。例如:
#include <iostream>
using namespace std;
class shape{
public:
virtual void draw(){cout<<"I am shape"<<endl;}
void fun(){draw();}
};
class circle:public shape{
public:
void draw(){cout<<"I am circle"<<endl;}
};
void main(){
circle oneshape;
oneshape.fun();
}
输出结果为:I am circle。
调用的是更改后的draw()函数。
虚函数与多态
我理解的多态就是相同的函数,不同的对象去调用会使用不同的定义。在C++中,主要使用虚函数实现多态的功能。
1、基类的指针或引用可以指向派生类,对于非虚函数,调用的函数实现方式取决与指针或引用的类型;
2、对于虚函数对于非虚函数,调用的函数实现方式取决与指针或引用指向的数据类型;
例如:
#include <iostream>
using namespace std;
class shape{
public:
virtual void draw(){cout<<"I am shape"<<endl;}
void fun(){draw();}
};
class circle:public shape{
public:
void draw(){cout<<"I am circle"<<endl;}
};
void main()
{
circle oneshape;
shape * A = &oneshape;
A.fun();
}
输出结果为:I am circle。
若没有使用虚函数,
则输出结果为:I am shape。