# 虚函数

1.虚函数的使用方法

## .基同类与派生类同时拥有的同名同参数表的函数，在设计时，最好将其声明为虚函数，只需在函数前面加上关键字virtual即可

#include<iostream>
using namespace std;
class Shape{
public:
void Printf(){
cout<<" The Shape has been called"<<endl;
}
};
class Rectangle:public Shape{
public:
void Printf(){
cout<<"The Rectangle has been called"<<endl;
}

};
class Circle:public Shape{
public:
void Printf(){
cout<<"he Circle has been called"<<endl;

}
};
void Print(Shape &a)
{

a.Printf();
}
void Print(Rectangle &a)
{

a.Printf();
}
void Print(Circle &a)
{

a.Printf();
}
int main()
{
Shape a;
Rectangle b;
Circle c;
Print(a);
Print(b);
Print(c);
return 0;
}


#include<iostream>
using namespace std;
class Shape{
public:
virtual void Printf(){
cout<<" The Shape has been called"<<endl;
}
};
class Rectangle:public Shape{
public:
void Printf(){
cout<<"The Rectangle has been called"<<endl;
}

};
class Circle:public Shape{
public:
void Printf(){
cout<<"he Circle has been called"<<endl;

}
};
void Print(Shape &a)
{

a.Printf();
}

int main()
{
Shape a;
Rectangle b;
Circle c;
Print(a);
Print(b);
Print(c);
return 0;
}


## 3.虚析构函数

#include<iostream>
using namespace std;
class A
{
public:
~A(){
cout<<"A destructor"<<endl;
};

};
class B:public A{

public:
~B(){
cout<<"B destructor"<<endl;
};
};
int main()
{
A *p=new B;
delete p;
return 0;
}


#include<iostream>
using namespace std;
class A
{
public:
virtual ~A(){
cout<<"A destructor"<<endl;
};

};
class B:public A{

public:
~B(){
cout<<"B destructor"<<endl;
};
};
int main()
{
A *p=new B;
delete p;
return 0;
}


posted @ 2019-10-25 20:07  Kevin,ChanD  阅读(196)  评论(0编辑  收藏  举报