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

#include <iostream>

using namespace std;
class Per
{
    friend class Stu;
private:
    string name;
    int age;
    int *ht;
    int *we;
public:
    Per()
    { cout << "无参构造" << endl;   }
    //构造函数
    Per(string name,int age,int ht,int we):name(name),age(age),ht(new int(ht)),we(new int(we))
    {
        cout << "Per:: 有参构造" << endl;
    }
    //拷贝构造
    Per(const Per &other):name(other.name),age(other.age),ht(new int(*(other.ht))),we(new int (*(other.we)))//深拷贝
    {
        cout << "Per:: 拷贝构造" << endl;
    }
    //拷贝赋值
    Per &operator=(const Per &other)
    {
        if(this != &other)
        {
            name = other.name;
            age = other.age;
            ht = new int(*(other.ht));
            we = new int(*(other.we));
        }
        cout << "拷贝赋值" << endl;
        return *this;
    }
    //析构函数
    ~Per()
    {
        delete ht;
        delete we;
        cout << "Per :: 析构函数" << endl;
    }
    void show()
    {
        cout << "&this=" << this << endl;
        cout << "name = " << name << endl;
        cout << "age = " << age << endl;
        cout << "ht = " << *ht << endl;
        cout << "we = " << *we << endl;
    }
};
class Stu
{
private:
    int socre;
    Per* p1;//嵌套另一个类
public:
    Stu()
    {
        cout << "Stu:: 无参构造" << endl;
    }
    Stu(int socre,Per p1):socre(socre),p1(new Per(p1))
    {
        cout << "Stu:: 有参构造函数" << endl;
    }
    Stu(const Stu &other):socre(other.socre), p1(new Per(*(other.p1)))
    {
        cout << "Stu :: 拷贝构造" << endl;
    }
    Stu &operator=(const Stu &other)
    {
        socre = other.socre;
        p1 = other.p1;
        cout << "Stu:: 拷贝赋值" << endl;
        return *this;
    }
    ~Stu()
    {
        delete p1;
        cout << "Stu:: 析构函数" << endl;
    }
    void show()
    {
        cout << "&this=" << this << endl;
        cout << "socre=" << socre << endl;
        cout << "name=" << p1->name << endl;
        cout << "age = " << p1->age << endl;
        cout << "ht = " << *(p1->ht) << endl;
        cout << "we = " << *(p1->we) << endl;
    }
};
int main()
{
    Per p1;
    Per p2("lisi",18,180,75);
    Per p3(p2);
    p1 = p3;
    cout << "&p1=" << &p1 << endl;
    cout << "&p2=" << &p2 << endl;
    cout << "&p3=" << &p3 << endl;
    p2.show();
    p3.show();
    p1.show();
    Stu s1;
    Stu s2(95,p1);
    Stu s3(s2);
    s1 = s3;
    s1.show();
    cout << "&s1=" << &s1 << endl;
    cout << "&s2=" << &s2 << endl;
    cout << "&s3=" << &s3 << endl;
    s2.show();
    s3.show();
    s1.show();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值