C++4d
#include <iostream>
#include <string>
using namespace std;class Per
{
private:
string name; // 姓名
int age; // 年龄
double* height; // 身高(指针,需动态分配内存)
double* weight; // 体重(指针,需动态分配内存)
public:
// 1. 普通构造函数:初始化成员,为指针分配内存
Per(string n = "无名", int a = 0, double h = 0.0, double w = 0.0) : name(n), age(a)
{
height = new double(h); // 为身高分配内存并赋值
weight = new double(w); // 为体重分配内存并赋值
cout << "Per 普通构造函数调用" << endl;
}// 2. 析构函数:释放指针指向的动态内存,防止内存泄漏
~Per()
{
delete height; // 释放身高的内存
delete weight; // 释放体重的内存
cout << "Per 析构函数调用" << endl;
}// 3. 拷贝构造函数:深拷贝(为新对象的指针分配独立内存)
Per(const Per& other) : name(other.name), age(other.age)
{
height = new double(*(other.height)); // 为新身高分配内存,复制值
weight = new double(*(other.weight)); // 为新体重分配内存,复制值
cout << "Per 拷贝构造函数调用" << endl;
}// 4. 拷贝赋值函数:先释放当前内存,再深拷贝新内容(防止自赋值)
Per& operator=(const Per& other)
{
if (this != &other)
{ // 防止“自赋值”(如 p = p;)
name = other.name;
age = other.age;
// 先释放当前对象的旧内存
delete height;
delete weight;
// 深拷贝新对象的内容
height = new double(*(other.height));
weight = new double(*(other.weight));
}
cout << "Per 拷贝赋值函数调用" << endl;
return *this; // 返回自身引用,支持链式赋值(如 p1 = p2 = p3;)
}// 辅助:显示成员信息(便于测试)
void show() const
{
cout << "姓名:" << name << ",年龄:" << age<< ",身高:" << *height << ",体重:" << *weight << endl;
}
};
class Stu
{
private:
double score; // 成绩
Per p1; // Per类的对象成员(会自动调用Per的构造/拷贝/析构)
public:
// 1. 普通构造函数:初始化成绩,并用Per对象初始化p1
Stu(double s = 0.0, const Per& p = Per()) : score(s), p1(p)
{
cout << "Stu 普通构造函数调用" << endl;
}// 2. 析构函数:p1是Per对象,会自动调用Per的析构,无需手动处理
~Stu()
{
cout << "Stu 析构函数调用" << endl;
}// 3. 拷贝构造函数:复制成绩,并调用Per的拷贝构造初始化p1
Stu(const Stu& other) : score(other.score), p1(other.p1)
{
cout << "Stu 拷贝构造函数调用" << endl;
}// 4. 拷贝赋值函数:复制成绩,并调用Per的拷贝赋值给p1(防止自赋值)
Stu& operator=(const Stu& other)
{
if (this != &other)
{ // 防止“自赋值”
score = other.score;
p1 = other.p1; // 调用Per的拷贝赋值函数
}
cout << "Stu 拷贝赋值函数调用" << endl;
return *this;
}// 辅助:显示成员信息(便于测试)
void show() const
{
cout << "成绩:" << score << endl;
p1.show(); // 调用Per的show方法
}
};
int main()
{
// 测试 Per 类
Per p("张三", 20, 175.5, 65.0);
p.show();Per p2 = p; // 调用 Per 拷贝构造
p2.show();Per p3("李四", 22, 180.0, 70.0);
p = p3; // 调用 Per 拷贝赋值
p.show();cout << "----------------" << endl;
// 测试 Stu 类
Stu s(90.5, p);
s.show();Stu s2 = s; // 调用 Stu 拷贝构造
s2.show();Stu s3(85.0, p3);
s = s3; // 调用 Stu 拷贝赋值
s.show();return 0;
}