C++day5

实现一个图形类(Shape),包含受保护成员属性:周长、面积,

                                                公共成员函数:特殊成员函数书写

定义一个圆形类(Circle),继承自图形类,包含私有属性:半径

                                                公共成员函数:特殊成员函数、以及获取周长、获取面积函数

定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度

                                                公共成员函数:特殊成员函数、以及获取周长、获取面积函数

在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。

代码:

头文件

#ifndef TEST_H
#define TEST_H
#include <iostream>
using namespace std;
class Shape
{
public:
    Shape();      //无参构造
    Shape(double l,double s);//有参构造
    ~Shape();//析构函数
protected:
    double l;   //图形周长
    double s;   //图形面积
};
class Circle:public Shape
{
public:
    Circle();//无参构造
    Circle(double l,double s,double r);//有参构造
    ~Circle();//析构函数
    double get_l(); //获取周长函数
    double get_s(); //获取面积函数
protected:
    double r;   //圆的半径
};
class Rect:public Shape
{
public:
    Rect();//无参构造
    Rect(double l,double s,double len,double wight);//有参构造
    ~Rect();//析构函数
    double get_l(); //获取周长函数
    double get_s(); //获取面积函数
protected:
    double len;   //矩形的长度
    double wight; //矩形的宽度
};
#endif // TEST_H

源代码

#include "test.h"
Shape::Shape()
{
    cout << "无参构造" << endl;
}
Shape::Shape(double l,double s):l(l),s(s)
{
    cout << "有参构造" << endl;
}
Shape::~Shape()//析构函数
{
    cout << "析构" << endl;
}
Circle::Circle()//无参构造
{
    cout << "无参构造" << endl;
}
Circle::Circle(double l,double s,double r):Shape(l,s),r(r)//有参构造
{
    cout << "有参构造" << endl;
}
Circle::~Circle()//析构函数
{
    cout << "析构" << endl;
}
double Circle::get_l() //获取周长函数
{
    return l;
}
double Circle::get_s() //获取面积函数
{
    return s;
}
Rect::Rect()//无参构造
{
    cout << "无参构造" << endl;
}
Rect::Rect(double l,double s,double len,double wight):Shape(l,s),len(len),wight(wight)//有参构造
{
    cout << "有参构造" << endl;
}
Rect::~Rect()//析构函数
{
    cout << "析构" << endl;
}
double Rect::get_l() //获取周长函数
{
    return l;
}
double Rect::get_s() //获取面积函数
{
    return s;
}

测试函数

#include "test.h"
int main()
{
    Circle test0(16,23,5);
    Rect test1(16,64,8,8);
    double l,s;
    l = test0.get_l();
    s = test0.get_s();
    cout << "test0.l = " << l << endl;
    cout << "test0.s = " << s << endl;
    l = test1.get_l();
    s = test1.get_s();
    cout << "test1.l = " << l << endl;
    cout << "test1.s = " << s << endl;
    return 0;
}

运行结果

思维导图

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值