题
实现一个图形类(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;
}
运行结果
思维导图