#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;} // 输出析构信息
C++day3
最新推荐文章于 2024-09-28 15:28:59 发布
本文详细介绍了C++中的两个类Per和Stu,包括它们的构造函数、拷贝构造函数和析构函数的实现,以及如何创建和操作对象的实例。
摘要由CSDN通过智能技术生成