2024.08.30
设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。
#include <iostream>
using namespace std;
class Per
{
private:
string name;
int age;
int *high;
int *weight;
public:
// 构造函数
Per()
{
high = nullptr;
weight = nullptr;
cout << "无参构造函数" << endl;
}
Per(string n, int a, int h, int w) : name(n), age(a), high(new int(h)), weight(new int(w))
{
cout << "有参构造函数" << endl;
}
// 深拷贝
Per(const Per &other) : name(other.name), age(other.age), high(new int(*other.high)), weight(new int(*other.weight))
{
cout << "拷贝构造函数执行" << endl;
}
// 析构函数
~Per()
{
delete high;
delete weight;
high = nullptr;
weight = nullptr;
cout << "析构函数执行" << endl;
}
void show()
{
cout << "name:" << name << endl;
cout << "age:" << age << endl;
cout << "high:" << *high << endl;
cout << "weight:" << *weight << endl;
}
};
class Stu
{
private:
float score;
Per p1;
public:
// 构造函数
Stu()
{
cout << "无参函数执行" << endl;
}
Stu(float s , string name , int age , int high , int weigh):score(s),p1(name,age,high,weigh)
{
cout << "有参构造函数执行" << endl;
}
// 拷贝构造函数
Stu(const Stu &other):score(other.score),p1(other.p1)
{
cout << "拷贝构造函数执行" << endl;
}
// 析构函数
~Stu()
{
cout << "析构函数执行" << endl;
}
void show()
{
cout << "score:" << score << endl;
p1.show();
}
};
int main()
{
Per p1; // 无参构造函数
Per p2("张三", 18, 170, 70); // 有参构造函数
Per p3(p2); // 拷贝构造函数
p3.show();
Per p4 = p3;
cout << "===================" << endl;
Stu s1;
Stu s2(100,"李四",18,170,70);
Stu s3(s2);
s3.show();
return 0;
}