继承—形状案例

本文探讨了在C++中创建形状类的继承结构,包括圆形、矩形等子类的实现。通过定义基类Shape,派生出Rectangle和Circle类,展示了如何封装属性和方法,以及如何使用这些类来创建具体的形状实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rectangle.hpp

//
//  rectangle.hpp
//  herite from shape
//
//

#ifndef rectangle_hpp
#define rectangle_hpp
#include "shape.h"

class Rectangle:public Shape{
    double width{1.0};
    double height{1.0};
public:
    Rectangle()=default;
    Rectangle(double w,double h);
    
    double getWidth() const;        //对象的状态不被改变
    void setWidth(double w);
    double getHeight() const;
    void setHeight(double h);
    
    double getArea() const;
};

#endif /* rectangle_hpp */

rectangle.cpp

#include "rectangle.hpp"

Rectangle::Rectangle(double w,double h):width{w},height{h}{}

double Rectangle::getWidth() const{return width};
void Rectangle::setWidth(double w){width=w;}
double Rectangle::getHeight()const{return height;}
void Rectangle::setHeight(double n){height=n;}

double Rectangle::getArea() const{
    return width*height;
}

circle.cpp

#include<iostream>
#include "circle.hpp"

Circle::Circle(double radius_){
    radius=radius_;
}

double Circle::getArea(){
    return (3.14*radius*radius);
}

double Circle::getRadius() const{
    return radius;
}

void Circle::setRaius(double radius){
    this->radius=radius;
}

circle.hpp


//补全Circle类,从Shape继承

#ifndef circle_hpp
#define circle_hpp
#include "shape.h"

class Circle:public Shape{
    double radius;
public:
    Circle();
    Circle(double radius_);
    double getArea();
    double getRadius() const;
    void setRaius(double radius);
};
#endif /* circle_hpp */

shape.h

ifndef shape_h
#define shape_h
#include<iostream>
#include<array>
#include<string>
using std::string;
using namespace std::string_literals;
enum class Color {
    white,black,red,green,blue,yellow,
};

class Shape{
private:
    Color color{Color::black};
    bool filled{false};
public:
    Shape()=default;
    Shape(Color color_,bool filled_){
        color=color_;
        filled=filled_;
    }

Color getColor(){return color;}
void setColor(Color color_){color=color_;}
bool isFilled(){return filled;}
void setFilled(bool filled_){filled=filled_;}

string toString(){
std::array<string,6>c{"white"s,"black"s,"red"s,"green"s,"blue"s,"yellow"s};
    return "Shape:"+c[static_cast<int>(color)]+" "+
    (filled ?"filled"s:"not filled"s);
    }
};

#endif /* shape_h */

mai.cpp

#include <iostream>
#include <string>
#include "shape.h"
#include "circle.hpp"
#include "rectangle.hpp"

// creat Shape/Circle/Rectangle object

int main() {
    Shape s1{Color::blue,false};
    Circle c1{3.9};
    Rectangle r1{4.0,1.0};
    std::cout<<s1.toString()<<std::endl;
    std::cout<<c1.toString()<<std::endl;
    std::cout<<r1.toString()<<std::endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值