设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。
#include <iostream>
using namespace std;
class Per //封装Per类
{
private: //私有
string name; //名字
int age; //年龄
int *height; //身高
int *weight; //体重
public: //公有
Per() {cout << "Per::无参构造函数" << endl;}
//初始化
Per(string name,int age,int h,int w):name(name),age(age),height(new int(h)),weight(new int(w))
{
cout << "Per::有参构造函数" << endl;
}
~Per()
{
cout << "Per::析构函数" << endl;
delete height;
delete weight;
}
void show()
{
cout << "姓名=" << name << endl;
cout << "年龄=" << age << endl;
cout << "身高=" << *height << endl;
cout << "体重=" << *weight << endl;
}
};
class Stu //封装Stu类
{
private: //私有
double score; //成绩
Per p1;
public:
Stu() {cout << "Stu::无参构造函数" << endl;}
Stu(double s,string name,int age,int height,int weight):score(s),p1(name,age,height,weight)
{
cout << "Stu::有参构造函数" << endl;
}
~Stu()
{
cout << "Stu::析构函数" << endl;
}
Stu(const Stu &other):score(other.score),p1(other.p1)
{
cout << "Stu::拷贝构造函数" << endl;
}
void show()
{
p1.show();
cout << "成绩=" << score << endl;
}
};
int main()
{
Stu s1(18,"张三",179,70,98);
s1.show();
Stu s2=s1;
s2.show();
return 0;
}