一、
设计一个Per类
类中包含私有成员:姓名、年龄、指针成员身高、体重,
再设计一个Stu类
类中包含私有成员:成绩、Per类对象p1
设计这两个类的构造函数、析构函数和拷贝构造函数
代码如下:
#include <iostream>
using namespace std;
class Per
{
private:
string name;
int age;
double *height;
double *weight;
public:
//Per无参构造函数(默认提供的函数)
Per()
{
cout << "这是Per::无参构造函数 " << endl;
};
//Per有参构造函数
Per(string name, int age, double height, double weight):name(name),age(age),height(new double(height)),weight(new double(weight))
{
cout << "姓名: " << Per::name << endl;
cout << "年龄: " << Per::age << endl;
cout << "身高: " << *(this->height) << endl;
cout << "体重: " << *(this->weight) << endl;
cout << "这是Per::有参构造函数 " << endl;
}
void show()
{
cout << "姓名: " << this->name << endl;
cout << "年龄: " << this->age << endl;
}
//析构函数
~Per()
{
delete height;
height = nullptr;
delete weight;
weight = nullptr;
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;
}
};
class Stu
{
private:
double score;
Per p1;
public:
//Stu无参构造函数
Stu()
{
cout << "这是Stu::无参构造函数 " << endl;
}
//Stu有参构造函数
Stu(double score, Per p1):score(score),p1(p1)
{
cout << "成员分数: " << this->score << endl;
p1.show();
cout << "这是Stu::有参构造函数 " << endl;
}
void show()
{
}
//析构函数
~Stu()
{
cout << "这是Stu::析构函数 " << endl;
}
//拷贝析构函数
Stu(const Stu &other):score(other.score),p1(other.p1)
{
cout << "这是Stu::拷贝析构函数 " << endl;
}
};
int main()
{
Per stu1("Mary",23,172,125);
cout << "-------------------------------------" << endl;
Stu p1(98,stu1);
return 0;
}
运行结果:
![](https://i-blog.csdnimg.cn/direct/5824e4f6478b408e8e728dcecf6a438d.png)
二、 思维导图
![](https://i-blog.csdnimg.cn/direct/c8098f677b914f27999b7e3c59d7ecd8.png)