纯虚函数

纯虚函数就是方便继承类的通用性,覆盖基类相同名字的函数。 格式就是 virtual + 类型 + 函数名字() = 0; 继承类就是 类型 + 函数名字() overried{}(意思就是覆盖了基类的虚函数,用当前的替代)

要说明的是纯虚函数的类型是什么,继承类就是什么,还不知道有什么方法能让他们不一样,如果会了就补上。

#include <bits/stdc++.h>
const double pi = acos(-1);
using namespace std;
class shape{ 
    public:
        virtual void area() = 0;   //这个就是虚函数。
};
class circle:public shape{
    int r;
    public:
        circle(int x = 0):r(x){}
        void area() override {            //继承类的覆盖
            cout << "The S of this circle: " << pi*r*r << endl;
        }
};
class rectangle:public shape{
    int width, length;
    public:
        rectangle(int x = 0, int y = 0):width(x),length(y){}
        void area() override{           //继承类的覆盖
            cout << "The S of this rectangle: " << width*length << endl;
        }
};

// 我代码段外那个不明白的就是如果虚函数类型是void,但是有继承类想用double类型,int类型,或者其他,就不行了, 有没有什么操作能更通用些。
int main(){ circle cir = circle(5); cir.area(); rectangle rec = rectangle(4, 5); rec.area(); return 0; }

 

posted @ 2020-04-28 16:51  philo_zhou  阅读(368)  评论(0编辑  收藏  举报