虚函数
学堂在线中郑莉老师对虚函数进行了详细的讲解
具体的代码如下
#include <iostream> using namespace std; class Base1 { public: virtual void display() const; //虚函数 }; void Base1::display() const { cout << "Base1::display()" << endl; } class Base2::public Base1 { public: virtual void display() const; }; void Base2::display() const { cout << "Base2::display()" << endl; } class Derived: public Base2 { public: virtual void display() const; }; void Derived::display() const { cout << "Derived::display()" << endl; } void fun(Base1 *ptr) { ptr->display(); } int main() { Base1 base1; Base2 base2; Derived derived; fun(&base1); fun(&base2); fun(&derived); return 0; }
对于郑莉老师的书籍[2]第344页8-5习题,书写如下的示例程序如下
#include <iostream> using namespace std; class Mammal{ public: virtual void speak(){}//虚函数声明 }; class Dog:public Mammal{ public: virtual void speak(){//虚函数实现 cout<<"I am a dog"<<endl; } }; class Cat:public Mammal{ public: virtual void speak(){ cout<<"I am a cat"<<endl; } }; class Pig:public Mammal{ }; int main(){ Dog dog; dog.speak(); Cat cat; cat.speak(); getchar(); return 0; }
虚函数更进一步的进化是纯虚函数,【2】中习题8-6的实现如下
#include <iostream> using namespace std; #define pi 3.1415926 class Shape{ //抽象类 public: virtual float getArea()=0; //纯(0)虚(virtual)函数 virtual float getPerim()=0; }; //长方形 class Rectangle : public Shape{ private: int width; int height; public: Rectangle(float w,float h):width(w),height(h){}; virtual float getArea(){ return width*height; } virtual float getPerim(){ return 2*(width+height); } }; //圆 class Circle : public Shape{ private: int radius;//半径 public: Circle(float r):radius(r){};//初始化 virtual float getArea(){ return pi*radius*radius; } virtual float getPerim(){ return 2*pi*radius; } }; int main(){ Rectangle rec(2,3); cout<<rec.getArea()<<endl; Circle cir(4); //抽象类不能实例化,只能做基类(鸡肋) cout<<cir.getPerim()<<endl; getchar(); return 0; }
【1】学堂在线
【2】c++ 语言程序设计