虚函数加vritual关键字,目的是为了实现多态性,可以通过基类的指针和引用调用派生类的对象,从而产生不同的效果。
#include<iostream>
using namespace std;
class Base1{
public:
virtual void display() const=0;//虚函数
};
class Base2:public Base1{
public:
void display() const;//覆盖基类的虚函数
};
void Base2::display() const{
cout<<"Base2::display()"<<endl;
}
class Derived:public Base2{
public:
void display() const;//覆盖基类的虚函数
};
void Derived::display()const{
cout<<"Dervied::display()"<<endl;
};
void fun(const Base1 *p){
p->display();
}
int main(){
Base2 base2;
Derived derived;
fun(&base2);
fun(&derived);
return 0;
}
纯虚函数不能在定义类中实现,但应该在能够实例化的派生类中实现。定义了纯虚函数的类为抽象类。
#include<iostream>
using namespace std;
class Base1{
public:
virtual void display() const=0;//纯虚函数
};
class Base2:public Base1{
public:
void display() const;//覆盖基类的虚函数
};
void Base2::display()const{
cout<<"Base2"<<endl;
}
class Derived:public Base2{
public:
void display()const;//覆盖基类的虚函数
};
void Derived::display()const{
cout<<"Derived"<<endl;
}
void fun(const Base1 *p){//参数为指向基类对象的指针
p->display();
}
int main(){
Base2 b;
Derived d;
fun(&b);
fun(&d);
return 0;
}
虚基类:虚基类是指虚继承中的基类,
#include<iostream>
using namespace std;
class Base0{//定义基类
public:
Base0(int v):var0(v){}
int var0;
void show() const{
cout<<var0<<endl;
}
};
class Base1:virtual public Base0{//Base0为虚基类
public:
Base1(int v):Base0(v){}
~Base1(){}
};
class Base2:virtual public Base0{//Base0为虚基类
public:
Base2(int v):Base0(v){}
};
class Derived:public Base1,public Base2{
public:
Derived(int v):Base1(v),Base2(v),Base0(v){}//构造函数要从最远派生类赋值
~Derived(){}//析构函数和普通类的构造函数没区别
};
int main(){
Derived d(2);
d.var0;
d.show();//直接调用虚基类的函数
return 0;
}