实现一个图形类(Shape),包含受保护成员属性:周长、面积,
公共成员函数:特殊成员函数书写
定义一个圆形类(Circle),继承自图形类,包含私有属性:半径
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。
![](https://img-blog.csdnimg.cn/0cf6bb98ae514611a758e1a77e46e011.png)
#include <iostream>
using namespace std;
class Shape//实现一个图形类
{
protected:
double zc;//周长
double mj;//面积
public:
Shape()//无参构造
{
cout<<"图形无参构造成功"<<endl;
}
Shape(double a,double b):zc(a),mj(b)//有参构造
{
cout<<"图形有参构造成功"<<endl;
}
~Shape(){}//析构函数
Shape(const Shape &other):zc(other.zc),mj(other.mj)//拷贝构造
{
cout<<"图形拷贝构造成功"<<endl;
}
Shape & operator=(const Shape &other)//拷贝赋值
{
if(this != &other) //确定不是自己给自己赋值
{
this->zc = other.zc;
this->mj = other.mj;
}
cout<<"拷贝赋值函数成功"<<endl;
return *this; //返回自身引用
}
virtual double get_zh()//获取周长函数
{
return zc;
}
virtual double get_mj()//获取面积函数
{
return mj;
}
};
class Circle:public Shape//定义一个圆形类,继承图形类
{
private:
double bj;//半径
public:
Circle()//无参构造
{
cout<<"圆形无参构造成功"<<endl;
}
Circle(double c):bj(c)//有参构造
{
cout<<"圆形有参构造成功"<<endl;
}
~Circle(){}//析构函数
Circle(const Circle &other):Shape(other),bj(other.bj)//拷贝构造
{
cout<<"圆形拷贝构造成功"<<endl;
}
Circle & operator=(const Circle &other)//拷贝赋值
{
if(this != &other) //确定不是自己给自己赋值
{
Shape::operator=(other);
this->bj = other.bj;
}
cout<<"拷贝赋值函数成功"<<endl;
return *this; //返回自身引用
}
double get_zh() override//获取周长函数
{
zc=3.14*2*bj;
return zc;
}
double get_mj() override//获取面积函数
{
mj=3.14*bj*bj;
return mj;
}
void show()
{
cout<<"半径为:"<<bj<<endl;
cout<<"周长为:"<<zc<<" 面积为:"<<mj<<endl;
}
};
class Rect:public Shape//定义一个矩形类,继承图形类
{
private:
double cd;//长度
double kd;//宽度
public:
Rect()//无参构造
{
cout<<"矩形无参构造成功"<<endl;
}
Rect(double c,double d):cd(c),kd(d)//有参构造
{
cout<<"矩形有参构造成功"<<endl;
}
~Rect(){}//析构函数
Rect(const Rect &other):Shape(other),cd(other.cd),kd(other.kd)//拷贝构造
{
cout<<"矩形拷贝构造成功"<<endl;
}
Rect & operator=(const Rect &other)//拷贝赋值
{
if(this != &other) //确定不是自己给自己赋值
{
Shape::operator=(other);
this->cd = other.cd;
this->kd = other.kd;
}
cout<<"拷贝赋值函数成功"<<endl;
return *this; //返回自身引用
}
double get_zh()//获取周长函数
{
zc=(cd+kd)*2;
return zc;
}
double get_mj()//获取面积函数
{
mj=cd*kd;
return mj;
}
void show()
{
cout<<"长为:"<<cd<<" 宽为:"<<kd<<endl;
cout<<"周长为:"<<zc<<" 面积为:"<<mj<<endl;
}
};
int main()
{
Circle c1(5);
double a=c1.get_zh();
double b=c1.get_mj();
c1.show();
Rect r1={6,8};
a=r1.get_zh();
b=r1.get_mj();
r1.show();
return 0;
}
五、思维导图
![](https://img-blog.csdnimg.cn/c09fd8ad946d4be99ca964a907d1803c.png)