版权声明:本文为博主原创文章,未经博主允许不得转载。如有问题,欢迎指正。 https://blog.csdn.net/zhouchangyu1221/article/details/89813212
// C++ 第五章:继承和虚函数
// 1.继承
// 基类的私有成员继承为子类中的更高级的私有成员,子类不可访问
// 如需访问,需调用基类中的公有函数
// 其余成员采取安全等级就高操作
// 构造函数和析构函数不被继承
#include<iostream>
#include<iomanip>
using namespace std;
class Shape
{
private:
float member;
public:
float area;
// 默认构造函数
Shape()
{
cout<<"基类默认构造函数:\n";
member=0;
}
Shape(float s)
{
cout<<"基类构造函数:\n";
member=s;
}
float getmem(){return member;}
~Shape()
{
cout<<"基类析构函数\n";
}
};
class Squ
{
private:
float len;
public:
Squ(float l)
{
cout<<"正方形构造函数:";
len=l;
cout<<len<<endl;
}
~Squ()
{
cout<<"正方形析构函数:";
cout<<len<<endl;
}
};
class Rect:public Shape
{
private:
float width;
float height;
Squ squ1;
Squ squ2;
public:
Rect():
squ2(0),squ1(0)
{
cout<<"子类默认构造函数"<<endl;
width=height=0;
area=0;
}
Rect(float l1,float l2,float w, float h,float m):
squ2(l2),squ1(l1),Shape(m)
{
cout<<"子类构造函数"<<endl;
width=w;
height=h;
area=w*h;
}
~Rect()
{
cout<<"子类析构函数\n";
}
};
int main(void)
{
Rect rec(3.0,5.0,3.0,5.0,1.0);
cout<<setprecision(2)<<setiosflags(ios::fixed|ios::showpoint);
cout<<"member:"<<rec.getmem()<<endl;
cout<<"面积:"<<rec.area<<endl;
return 0;
}