实现一个图形类(Shape),包含受保护成员属性:周长、面积,
公共成员函数:特殊成员函数书写
定义一个圆形类(Circle),继承自图形类,包含私有属性:半径
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
定义一个矩形类(Rect),继承自图形类,包含私有属性:长度、宽度
公共成员函数:特殊成员函数、以及获取周长、获取面积函数
在主函数中,分别实例化圆形类对象以及矩形类对象,并测试相关的成员函数。
#include <iostream>
using namespace std;
class Shape
{
protected:
double round;
double area;
public:
Shape()
{
cout<<"无参构造"<<endl;
}
Shape(double r,double a):round(r),area(a)
{
cout<<"有参构造"<<endl;
}
~Shape()
{
cout<<"析构函数"<<endl;
}
Shape(const Shape &other):round(other.round),area(other.area)
{
cout<<"拷贝构造"<<endl;
}
Shape & operator=(const Shape &other)
{
this->area=other.area;
this->round=other.round;
cout<<"拷贝赋值"<<endl;
return *this;
}
Shape & operator=(Shape &&other)
{
this->area=other.area;
this->round=other.round;
cout<<"移动赋值"<<endl;
return *this;
}
};
class Circle:public Shape
{
private:
double bj;
public:
Circle() {}
Circle(double r):bj(r)
{
cout<<"有参构造"<<endl;
}
~Circle()
{
cout<<"析构函数"<<endl;
}
Circle(const Circle &other):Shape(other.round,other.area),bj(other.bj)
{
cout<<"拷贝构造"<<endl;
}
Circle & operator=(const Circle &other)
{
this->area=other.area;
this->round=other.round;
this->bj=other.bj;
cout<<"拷贝赋值"<<endl;
return *this;
}
Circle & operator=(Circle &&other)
{
this->area=other.area;
this->round=other.round;
this->bj=other.bj;
cout<<"移动赋值"<<endl;
return *this;
}
void zc()
{
this->round=this->bj*2*(3.14);
cout<<"周长="<<round<<endl;
}
void mj()
{
this->area=this->bj*this->bj*(3.14);
cout<<"面积="<<area<<endl;
}
void show()
{
cout<<"周长="<<round<<endl;
cout<<"面积="<<area<<endl;
}
};
class Rect:public Shape
{
private:
double hight;
double wight;
public:
Rect() {}
Rect(double h,double w):hight(h),wight(w)
{
cout<<"有参构造"<<endl;
}
~Rect()
{
cout<<"析构函数"<<endl;
}
Rect(const Rect &other):Shape(other.round,other.area),hight(other.hight),wight(other.wight)
{
cout<<"拷贝构造"<<endl;
}
Rect & operator=(const Rect &other)
{
this->area=other.area;
this->round=other.round;
this->hight=other.hight;
this->wight=other.wight;
cout<<"拷贝赋值"<<endl;
return *this;
}
Rect & operator=(Rect &&other)
{
this->area=other.area;
this->round=other.round;
this->hight=other.hight;
this->wight=other.wight;
cout<<"移动赋值"<<endl;
return *this;
}
void zc()
{
this->round=(this->hight+this->wight)*2;
cout<<"周长="<<round<<endl;
}
void mj()
{
this->area=this->hight*this->wight;
cout<<"面积="<<area<<endl;
}
void show()
{
cout<<"周长="<<round<<endl;
cout<<"面积="<<area<<endl;
}
};
int main()
{
Circle c1(10);
c1.zc();
c1.mj();
Circle c2(c1);
c2.show();
Circle c3;
c3=c1;
c3.show();
Circle c4;
c4=move(c3);
c3.show();
c4.show();
cout<<"******************************************"<<endl;
Rect r1(10,5);
r1.mj();
r1.zc();
Rect r2=r1;
r2.show();
Rect r3;
r3=r1;
r3.show();
return 0;
}