要求:
设计一个Per类。类中包含私有成员:姓名、年龄、指针成员身高、体重;
再设计一个Stu类,类中包含私有成员:成绩、Per类对象 p1;
设计这两个类的构造函数、析构函数和拷贝构造函数。
#include <iostream>using namespace std;
class Per
{string name; //姓名int age; //年龄int *h; //身高int *w; //体重
public:Per():h(new int),w(new int)//在不传参的情况下,给指针成员h、w用堆区的空间初始化{cout << "Per无参构造" << endl;}Per(int h,int w):h(new int(h)),w(new int (w)) //在参数为整型变量的情况下,让h、w指向堆区申请的空间//但是把这片空间的内容,用传过来的整型变量h、w初始化{cout << "Per的有参构造" << endl;}//获取姓名赋值到结构体中void get_name(string name);//获取年龄赋值到结构体中void get_age(int age);//析构函数~Per(){//在析构之前释放堆区空间cout << "准备释放空间:" << h << endl;cout << "准备释放空间:" << w << endl;delete h;delete w;h = nullptr;w = nullptr;cout << "Per的析构函数" << endl;}void show_Msg(); //输出信息//拷贝构造函数Per(Per &other){this->name = other.name;this->age = other.age;h = new int;w = new int;*h = *(other.h);*w = *(other.w);cout << "Per的拷贝构造函数" << endl;}
};
class Stu
{float score;Per p1;
public://void get_score();Stu(){cout << "Stu的无参构造函数" << endl;}Stu(float score,Per p1){this->p1=p1;this->score = score;cout << "Stu的有参构造函数" << endl;}~Stu(){//在析构之前释放堆区的空间cout << "Stu的析构函数" << endl;}Stu(Stu &other):score(other.score),p1(other.p1){cout << "Stu的拷贝构造函数" << endl;}//输出信息void show_Stu_Msg();
};//--------------------------------主函数------------------------------------
int main()
{Per s; //无参构造Per s1(180,50); //有参构造,传递h和w的值s1.get_name("zhangsan"); //赋值s1.get_age(18); //赋值s1.show_Msg(); //赋值Per s2 = s1; //申请了一个Per的类对象,将s1的值初始化给s2s2.show_Msg();Stu p; //无参构造Stu z1(98,s1); //有参构造z1.show_Stu_Msg(); //输出z1中的信息(float、Per p1)return 0;
}//---------------------------------函数-------------------------------------
void Per::get_name(string name)//获取姓名赋值到结构体中
{this->name = name;cout << "姓名已保存: " << this->name << endl;
}void Per::get_age(int age) //获取年龄赋值到结构体中
{this->age = age;cout << "年龄已保存: " << this->age << endl;
}void Per::show_Msg()//输出Per信息
{cout << "姓名:"<<name << " 年龄:"<<age << " 身高:"<<*h << " 体重:"<<*w << endl;
}void Stu::show_Stu_Msg()//输出Stu信息
{p1.show_Msg();cout << "成绩为: " << score << endl;
}