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

运行结果:

思维导图:

相关推荐
敢敢のwings22 分钟前
智元 GO-2 与 AgiBot-World 深度解读
开发语言·后端·golang
yaoxin52112331 分钟前
503. Java 反射 - 编写 ServiceFactory 类
java·开发语言·python
一个帅气昵称啊1 小时前
.Net C# AI智能体开发-快速开始
开发语言·c#·.net
冬夜戏雪1 小时前
agent的trace 和eval
开发语言·前端·javascript
Sagittarius_A*1 小时前
Burst Lab | PHP 审计 13|反序列化(三):POP 链构造与 Gadget Chain 分析
开发语言·web安全·php·代码审计·反序列化
职场的momo2 小时前
11个后端与AI岗位同时开放:Java、网关、推理优化怎么匹配
java·开发语言·人工智能
蓝速科技2 小时前
蓝速科技丨新旧楼宇混杂场景下会议室预约门牌屏一体化改造方案
开发语言·科技·php
梦想的旅途23 小时前
Python实现企业微信文本消息发送
开发语言·python·企业微信
大鹏说大话3 小时前
美业微信会员系统哪个好
开发语言
程序员与背包客_CoderZ4 小时前
高性能分布式KV存储引擎RocksDB入门与C/C++编码实战
c语言·开发语言·数据库·c++·分布式·分布式数据库·rocksdb