C++day3

本文详细介绍了C++中的两个类Per和Stu,包括它们的构造函数、拷贝构造函数和析构函数的实现,以及如何创建和操作对象的实例。
摘要由CSDN通过智能技术生成
#include <iostream> // 包含输入输出流库

using namespace std; // 使用标准命名空间

class Per // 定义类 Per
{
private: // 私有成员
    string name; // 字符串类型的姓名
    int age; // 整型的年龄
    int *h; // 整型指针 身高
    int *t; // 整型指针 体重
public: // 公有成员
    Per(string name,int age,int h,int t); // 构造函数
    Per(const Per &other); // 拷贝构造函数
    void show(); // 显示函数
    ~Per(); // 析构函数
};
class Stu // 定义类 Stu
{
private: // 私有成员
    Per usr; // 类型为 Per 的对象 usr
    double score; // 双精度浮点型的分数
public: // 公有成员
    Stu(string name,double score,int age,int h,int t); // 构造函数
    void show(); // 显示函数
    ~Stu(); // 析构函数
};
int main() // 主函数
{
    Stu stu("张三",98,18,180,150); // 创建 Stu 类对象 stu
    stu.show(); // 调用 stu 的显示函数
    Stu stu1(stu); // 用 stu 初始化 stu1
    stu1.show(); // 调用 stu1 的显示函数
    return 0; // 返回 0
}
void Per::show() // Per 类的显示函数
{
    cout << name << endl; // 输出姓名
    cout << age << endl; // 输出年龄
    cout << *h << endl; // 输出 h 指向的值
    cout << *t << endl; // 输出 t 指向的值
}
Per::Per(string name,int age,int h,int t):name(name),age(age),h(new int(h)),t(new int(t)) // Per 类的构造函数
{cout << "Per构造" << endl;} // 输出构造信息
Per::Per(const Per &other):name(other.name),age(other.age),h(new int(*(other.h))),t(new int(*(other.t))) // Per 类的拷贝构造函数
{cout << "Per拷贝构造" << endl;} // 输出拷贝构造信息
Per::~Per() // Per 类的析构函数
{
    delete h; // 释放 h 指向的内存
    delete t; // 释放 t 指向的内存
    h = nullptr; // 将 h 指针置空
    t = nullptr; // 将 t 指针置空
    cout << "Per析构" << endl; // 输出析构信息
}
void Stu::show() // Stu 类的显示函数
{
    usr.show(); // 调用 usr 的显示函数
    cout << score << endl; // 输出分数
}
Stu::Stu(string name,double score,int age,int h,int t):score(score),usr(name,age,h,t) // Stu 类的构造函数
{cout << "Stu构造" << endl;} // 输出构造信息
Stu::~Stu() // Stu 类的析构函数
{cout << "Stu析构" << endl;} // 输出析构信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值