【0823作业】C++:实现类嵌套,以及其构造函数、析构函数和拷贝构造函数

要求:

        设计一个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的值初始化给s2
    s2.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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值