实现一个图形类(Shape),包含受保护成员属性:周长、面积,
公共成员函数:特殊成员函数书写
定义一个圆形类(Circle),继承自图形类,包含私有属性:半径
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。
#include <iostream>using namespace std;class Shape
{
protected:double c; //周长double s; //面积public:Shape(){cout<<"无参构造函数"<<endl;}Shape(double c1, double s1):c(c1), s(s1){cout<<"有参构造函数"<<endl;}~Shape(){cout<<"析构函数"<<endl;}//拷贝构造Shape(const Shape &other):c(other.c), s(other.s){cout<<"拷贝构造"<<endl;}};//定义一个圆形类
class Circle:public Shape
{
private:double r; //半径public:Circle(){cout<<"无参构造函数"<<endl;}Circle(double c1, double s1, double r1):Shape(c1, s1), r(r1){cout<<"有参构造函数"<<endl;}~Circle(){cout<<"析构函数"<<endl;}//拷贝构造Circle(const Circle &other):Shape(other.c, other.s), r(other.r){cout<<"拷贝构造"<<endl;}//获取周长void get_c(double r){c = 2*r*3.14;cout<<"该圆的周长为"<<c<<endl;}//获取面积void get_s(double r){s = 2*r*r*3.14;cout<<"该圆的面积为"<<s<<endl;cout<<endl;}
};//定义一个矩形类
class Rect:public Shape
{
private:double h; //高double w; //宽public:Rect(){cout<<"无参构造函数"<<endl;}Rect(double c1, double s1, double h1, double w1):Shape(c1, s1), h(h1), w(w1){cout<<"有参构造函数"<<endl;}~Rect(){cout<<"析构函数"<<endl;}//拷贝构造Rect(const Rect &other):Shape(other.c,other.s), h(other.h), w(other.w){cout<<"拷贝构造"<<endl;}//获取周长void get_c(double h,double w){c = 2*(h+w);cout<<"该矩形的周长为"<<c<<endl;}//获取面积void get_s(double h, double w){s = h*w;cout<<"该矩形的面积为"<<s<<endl;cout<<endl;}
};int main()
{Circle a; //圆类对象a.get_c(5); //圆周长a.get_s(5); //圆面积Rect b; //矩形类对象b.get_c(4,5); //周长b.get_s(4,5); //面积return 0;
}