继承 代码
#include <iostream>
#define PI 3.14
using namespace std;
class Shape
{
protected:
double perimeter;
double area;
public:
Shape() {
cout<<"Shape::无参构造"<<endl;
}
Shape(double perimeter,double area):perimeter(perimeter),area(area){
cout<<"Shape::有参构造"<<endl;
}
~Shape(){
cout<<"Shape::析构函数"<<endl;
}
Shape(const Shape &other):perimeter(other.perimeter),area(other.area)
{
cout<<"Shape::拷贝构造"<<endl;
}
Shape& operator=(const Shape &other){
if(this!=&other)
{
this->area = other.area;
this->perimeter = other.perimeter;
}
cout<<"Shape::拷贝赋值"<<endl;
return *this;
}
};
class Circle:public Shape
{
private:
double r;
public:
Circle() {
cout<<"Shape::无参构造"<<endl;
}
Circle(double r):r(r)
{
cout<<"Shape::有参构造"<<endl;
}
~Circle()
{
cout<<"Shape::析构函数"<<endl;
}
Circle(const Circle &other):Shape(other.perimeter,other.area),r(other.r)
{
cout<<"Shape::拷贝构造"<<endl;
}
Circle& operator=(const Circle &other){
if(this!=&other)
{
this->area = other.area;
this->perimeter = other.perimeter;
this->r = other.r;
}
cout<<"Shape::拷贝赋值"<<endl;
return *this;
}
void get_c_s()
{
this->perimeter = 2*PI*this->r;
this->area = PI*r*r;
cout<<"周长是:"<<this->perimeter<<endl;
cout<<"面积是:"<<this->area<<endl;
}
};
class Rect:public Shape
{
private:
double len;
double wid;
public:
Rect() {
cout<<"Shape::无参构造"<<endl;
}
Rect(double len,double wid):len(len),wid(wid)
{
cout<<"Shape::有参构造"<<endl;
}
~Rect()
{
cout<<"Shape::析构函数"<<endl;
}
Rect(const Rect &other):len(other.len),wid(other.wid)
{
cout<<"Shape::拷贝构造"<<endl;
}
Rect& operator=(const Rect &other){
if(this!=&other)
{
this->len = other.len;
this->wid = other.wid;
}
cout<<"Shape::拷贝赋值"<<endl;
return *this;
}
void get_c_s()
{
this->perimeter = 2*(len+wid);
this->area = len*wid;
cout<<"周长是:"<<this->perimeter<<endl;
cout<<"面积是:"<<this->area<<endl;
}
};
int main()
{
Circle c1(3);
c1.get_c_s();
//拷贝构造
Circle c2 = c1;
c2.get_c_s();
//拷贝赋值
Circle c3;
c3 = c2;
c3.get_c_s();
cout<<"-----------------------------------"<<endl;
Rect r1(4,6);
r1.get_c_s();
//拷贝构造
Rect r2 = r1;
r2.get_c_s();
//拷贝赋值
Rect r3;
r3 = r2;
r3.get_c_s();
return 0;
}
思维导图