C++作业3

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

代码:

cpp 复制代码
#include <iostream>

using namespace std;

class Per
{
private:
    string name;
    int age;
    double *height;
    double *weight;
public:
    Per()
    {
        cout << "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 &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 &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;
}

运行结果:

思维导图:

相关推荐
じ☆ve 清风°10 分钟前
滑动窗口算法详解与C++实现
开发语言·c++·算法
苕皮蓝牙土豆15 分钟前
C++ map & multimap 容器:赋值、排序、大小与删除操作
开发语言·c++
Villiam_AY21 分钟前
Go 后端中双 token 的实现模板
开发语言·后端·golang
DjangoJason28 分钟前
计算机网络 : Socket编程
linux·服务器·开发语言·笔记·计算机网络
映秀小子30 分钟前
C语言链表的操作
c语言·开发语言·链表
虾球xz38 分钟前
游戏引擎学习第293天:移动Familiars
c++·学习·游戏引擎
救救孩子把44 分钟前
Mac 环境下 JDK 版本切换全指南
java·开发语言·macos
我们的五年1 小时前
【Qt】Qt常见控件的相关知识点
开发语言·qt
孙同学_1 小时前
【C++】map和set的使用
开发语言·c++
Bugabooo1 小时前
python打卡DAY22
开发语言·python