实现一个图形类(Shape),包含受保护成员属性:周长、面积,
公共成员函数:特殊成员函数书写
定义一个圆形类(Circle),继承自图形类,包含私有属性:半径
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。
#include <iostream>
#define PI 3.14
using namespace std;
class Shape
{
protected:
double permimeter;
double area;
public:
Shape()
{
cout<<"shape无参构造"<<endl;
}
Shape(double permimeter, double area):permimeter(permimeter),area(area)
{
cout<<"shape有参构造函数"<<endl;
}
~Shape()
{
cout<<"shape析构函数"<<endl;
}
Shape(const Shape &other):permimeter(other.permimeter),area(other.area)
{
cout<<"shape拷贝构造函数"<<endl;
}
const Shape &operator=(const Shape &other)
{
this->permimeter = other.permimeter;
this->area = other.area;
cout<<"shape拷贝赋值函数"<<endl;
return *this;
}
Shape(Shape && other):permimeter(other.permimeter),area(other.area)
{
cout<<"shape移动构造"<<endl;
}
Shape &operator=(Shape &&other)
{
this->area = other.area;
this->permimeter = other.permimeter;
return *this;
cout<<"移动赋值 = "<<endl;
return *this;
}
};
class Circle:public Shape
{
private:
double rad;
public:
Circle()
{
cout<<"circle无参构造"<<endl;
}
Circle(double r):Shape(2*PI*r, PI*r*r),rad(r)
{
cout<<"circle有参构造"<<endl;
}
~Circle()
{
cout<<"circle析构函数"<<endl;
}
Circle(const Circle &other):rad(other.rad)
{
cout<<"circle拷贝构造函数"<<endl;
}
double get_permimeter()
{
return permimeter;
}
double get_area()
{
return area;
}
};
class Rect:public Shape
{
private:
double length;
double width;
public:
Rect()
{
cout<<"rect无参构造"<<endl;
}
Rect(double l, double w):Shape(2*l+2*w, l*w),length(l),width(w)
{
cout<<"rect有参构造"<<endl;
}
~Rect()
{
cout<<"rect析构函数"<<endl;
}
double get_permimeter()
{
return permimeter;
}
double get_area()
{
return area;
}
};
int main()
{
Circle c(3);
cout<<"圆形面积 = "<<c.get_area()<<endl;
cout<<"圆形周长 = "<<c.get_permimeter()<<endl;
Rect r(4,5);
cout<<"矩形周长 = "<<r.get_permimeter()<<endl;
cout<<"矩形面积 = "<<r.get_area()<<endl;
return 0;
}