C++抽象类的继承

先定义一个抽象类shape,方法getArea()还未实现

class shape {
public:
    virtual double getArea()=0;
private:
    double width;
    double height;
public:
    shape(double width, double height) {
        this->width=width;
        this->height=height;
    }

public:
    double getWidth() const {
        return this->width;
    }

    void setWidth(double width) {
        this->width=width;
    }

    double getHeight() const {
        return this->height;
    }

    void setHeight(double height) {
        this->height=height;
    }
};

然后定义一个Rectangle类继承shape类,在类中实现shape的虚函数getArea()

class rectangle: public shape {
public:
    double getArea() {
        return this->getWidth()*this->getHeight();
    }
    rectangle(double width, double height) : shape(width, height) {}
};

最后在main函数中实现

#include 
#include "rectangle.h"

int main() {
    rectangle *r= new rectangle(4, 5.5);
    std::cout<getArea()<

输出是22

你可能感兴趣的:(c++)