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;
}

运行结果:

思维导图:

相关推荐
快乐的划水a38 分钟前
解释器模式及优化
c++·设计模式·解释器模式
##学无止境##1 小时前
解锁Java分布式魔法:CAP与BASE的奇幻冒险
java·开发语言·分布式
岁忧1 小时前
(LeetCode 每日一题) 498. 对角线遍历 (矩阵、模拟)
java·c++·算法·leetcode·矩阵·go
做一位快乐的码农1 小时前
基于Spring Boot的旅行足迹分享社区的设计与实现/基于java的在线论坛系统
java·开发语言·spring boot
kyle~2 小时前
C/C++---前缀和(Prefix Sum)
c语言·c++·算法
YxVoyager4 小时前
【C++标准库】<ios>详解基于流的 I/O
c语言·c++
code bean6 小时前
【C#】获取不重复的编码(递增,非GUID)
开发语言·c#
阿里嘎多哈基米6 小时前
二、JVM 入门——(三)栈
java·开发语言·jvm·线程·
雷达学弱狗6 小时前
anaconda本身有一个python环境(base),想用别的环境就是用anaconda命令行往anaconda里创建虚拟环境
开发语言·python
燃尽余火7 小时前
Knife4j 文档展示异常的小坑
java·开发语言·spring