c++day3

文章介绍了如何在C++中设计Per类和Stu类,包含姓名、年龄、身高、体重等私有成员,并实现无参和有参构造函数、析构函数以及深拷贝构造函数。还展示了如何在Stu类中使用Per对象,以及内存管理的相关操作。
摘要由CSDN通过智能技术生成

1> 思维导图

2>

设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。

#include <iostream>

using namespace std;

class Per{
    string name;
    int age;
    float *height;
    float *weight;
public:
    Per()
    {
        cout << "Per的无参构造函数" << endl;
    }
    Per(string name,int age,float *height,float *weight)
    {
        this->name = name;
        this->age= age;
        this->height = height;
        this->weight = weight;
        cout << "Per的有参构造函数" << endl;
    }
    Per(Per &other)
    {
        this->name = other.name;
        this->age= other.age;
        height = new float;
        weight = new float;
        *height = *(other.height);
        *weight = *(other.weight);
        cout << "Per的深拷贝构造函数" << endl;
    }
    void set_h(float a)
    {
        *height = a;
    }
    void set_w(float b)
    {
        *weight = b;
    }
    ~Per()
    {
        cout << "准备释放堆区空间" << endl;
        delete height;
        delete weight;
        height = nullptr;
        weight = nullptr;
        cout << "Per的析构函数" << endl;
    }
    void show()
    {
        cout << "姓名:" << name << endl;
        cout << "年龄:" << age << endl;
        cout << "身高:" << *height << endl;
        cout << "体重:" << *weight << endl;
    }
};
class Stu{
    int score;
public:
    Per p1;
public:
    Stu(int score,string name,int age,float *height,float *weight):score(score),p1{name,age,height,weight}
    {

        cout << "Stu的有参构造函数" << endl;
    }
    Stu()
    {
        cout << "Stu的无参构造函数" << endl;
    }
    void show()
    {
        cout << "Stu中的成绩=" << score << endl;
    }
};
int main()
{
    float *height = new float;
    *height = 188.2;
    float *weight = new float;
    *weight = 75.5;
    Stu s1(99,"亚索",25,height,weight);
    Stu s2=s1;
    cout << "s1中的个人信息" << endl;
    s1.show();
    s1.p1.show();
    cout << "s2中的个人信息" << endl;
    s2.show();
    s2.p1.show();
    cout << "s2修改后中的个人信息" << endl;
    s2.p1.set_h(180.5);
    s2.p1.set_w(80.5);
    s2.show();
    s2.p1.show();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值