zoukankan      html  css  js  c++  java
  • 纯虚函数

    纯虚函数就是方便继承类的通用性,覆盖基类相同名字的函数。 格式就是 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; }
  • 相关阅读:
    第二次站立会议4
    第二次站立会议3
    建议总结
    对搜狗输入法的个人评价
    第二期站立会议10
    典型用户和用户场景描述
    第二期站立会议9
    第二期站立会议8
    第二期站立会议7
    第二期站立会议6
  • 原文地址:https://www.cnblogs.com/philo-zhou/p/12795323.html
Copyright © 2011-2022 走看看