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

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

代码

#include <iostream>

using namespace std;

class Per
{
private:
    string name;
    int age;
    double *height;
    double *weight;
public:
    Per()
    {
        cout &lt;&lt; "per无参" << endl;
    }

    Per(string name,int age,double height,double weight):name(name),age(age),height(new double(height)),weight(new double(weight))
    {
        cout << "per有参" << endl;
    }

    Per(const Per &amp;other):name(other.name),age(other.age),height(new double(*(other.height))),weight(new double(*(other.weight)))
    {
        cout << "per拷贝" << endl;
    }

    ~Per()
    {
        delete height;
        delete height;
        height = nullptr;
        weight = nullptr;
        cout << "per析构" << endl;
    }

    void show();

};

void Per::show()
{
    cout << "name:" << name << endl;
    cout << "age:" << age << endl;
    cout << "height:" << *height << endl;
    cout << "weight:" << *weight << endl;
}

class Stu
{
private:
    double score;
    Per p1;
public:
    Stu()
    {
       cout << "stu无参" << endl;
    }

    Stu(double score,string name,int age,double height,double weight):score(score),p1(name,age,height,weight)
    {
        cout << "stu有参" << endl;
    }

    Stu(const Stu &amp;other):score(other.score),p1(other.p1)
    {
        cout << "stu拷贝" << endl;
    }

    ~Stu()
    {
        cout << "stu析构" << endl;
    }

    void show();
};

void Stu::show()
{
    cout << "score:" << score << endl;
    p1.show();
}

int main()
{
    Per s1("张三",18,1.7,120);
    s1.show();
    cout << "-----------------------" << endl;
    Per s2(s1);
    s2.show();
    cout << "-----------------------" << endl;
    Stu s3(98,"李四",21,1.8,125);
    s3.show();
    cout << "-----------------------" << endl;
    Stu s4(s3);
    s4.show();
    return 0;
}

运行结果

思维导图:

原文地址:https://blog.csdn.net/qq_56986199/article/details/134719117

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_20982.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注