实现一个图形类(Shape),包含受保护成员属性:周长、面积,
公共成员函数:特殊成员函数书写
定义一个圆形类(Circle),继承自图形类,包含私有属性:半径
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。
#include <iostream>
using namespace std;
const double pi=3.14;
class Shape{
protected:
double around;
double area;
public:
Shape():around(0),area(0){}
Shape(const Shape &other):around(other.around),area(other.area){}
Shape & operator=(const Shape &other){
this->around = other.around;
this->area=other.area;
return *this;
}
~Shape(){}
Shape(Shape &&other):around(other.around),area(other.area){}
Shape &operator=(Shape&&) = default;
};
class Circle:public Shape{
private:
double rad;
public:
Circle():rad(0){} //无参构造
Circle(const Circle &other):Shape(other),rad(other.rad){} //拷贝构造
Circle & operator =(const Circle &other){ //赋值拷贝
Shape::operator=(other);
this->rad=other.rad;
return *this;
}
~Circle(){}; //析构函数
Circle(Circle &&other):rad(other.rad){ //位移构造
}
Circle &operator=(Circle &&) = default; //赋值位移
double getrad(double ra){
if(ra<=0){
cout<<"输入的半径有误"<<endl;
return -1;
}
rad=ra;
around=2*pi*ra;
area=pi*ra*ra;
return 0;
}
void showrad(){
cout<<"半径"<<rad<<endl;
}
void outaround(){
cout<<"周长"<<around<<endl;
}
void outarea(){
cout<<"面积为"<<area<<endl;
}
};
class Rect:public Shape{
private:
double chang;
double kuan;
public:
Rect():chang(0),kuan(0){}
Rect(const Rect &other):Shape(other),chang(other.chang),kuan(other.kuan){}
Rect & operator =(const Rect &other){
Shape::operator=(other);
this->chang=other.chang;
this->kuan=other.kuan;
return *this;
}
~Rect(){};
Rect(Rect &&other):chang(other.chang),kuan(other.kuan){}
Rect &operator=(Rect &&) = default;
double getck(double ca,double ka){
if(ca<=0||ka<=0){
cout<<"输入的长或宽有误"<<endl;
return -1;
}
chang=ca;
kuan=ka;
area=ca*ka;
around=(ca+ka)*2;
return 0;
}
void showck(){
cout<<"长"<<chang<<endl<<"宽"<<kuan<<endl;
}
void outaround(){
cout<<"周长为"<<around<<endl;
}
void outarea(){
cout<<"面积为"<<area<<endl;
}
};
int main()
{
Circle c1;
c1.getrad(2);
Circle c2;
c2=c1;;
c2.outaround();
c2.showrad();
Rect r1;
r1.getck(2,3);
r1.outarea();
Rect r2;
r2=r1;
r2.showck();
r2.outarea();
r2.outaround();
return 0;
}