设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。
代码:
#include <iostream>
using namespace std;
class Per
{
private:
string name;
int age;
double *hight;
double *weight;
public:
Per()
{
cout << "Per::无参构造函数" << endl;
}
Per(string name,int age,double h,double w):name(name),age(age),hight(new double(h)),weight(new double(w))
{
cout << "Per::有参构造函数" << endl;
cout << name << " " << age << " " << *hight <<" " << *weight << endl;
}
~Per()
{
delete (hight);
delete (weight);
hight = nullptr;
weight = nullptr;
cout << "Per::析构函数" << endl;
}
Per(const Per &other):name(other.name),age(other.age),hight(new double(*(other.hight))),weight(new double(*(other.weight)))
{
cout << "Per::拷贝构造函数" << endl;
cout << name << " " << age << " " << *hight <<" " << *weight << endl;
}
void show()
{
cout << name << " " << age << " " << *hight <<" " << *weight << " ";
}
};
class Stu
{
private:
double score;
Per p1;
public:
Stu()
{
cout << "Stu::无参构造函数" << endl;
}
Stu(double score, string name, int age, double hight, double weight):score(score),p1(name,age,hight,weight)
{
cout << "Stu::有参构造函数" << endl;
p1.show();
cout << score << endl;
}
~Stu()
{
cout << "Stu::析构函数" << endl;
}
Stu(const Stu &other):score(other.score),p1(other.p1)
{
cout << "Stu::拷贝构造函数" << endl;
p1.show();
cout << score << endl;
}
};
int main()
{
cout << "请输入姓名、年龄、身高、体重、成绩:" << endl;
string name;
int age;
double hight,weight,score;
cin >> name >> age >> hight >> weight >> score;
Stu s1(score,name,age,hight,weight);
cout << "__________________________________" << endl;
cout << "请输入姓名、年龄、身高、体重、成绩:" << endl;
cin >> name >> age >> hight >> weight;
Per p1(name,age,hight,weight);
cout << "__________________________________" << endl;
Stu s2(s1);
cout << "__________________________________" << endl;
Per p2(p1);
return 0;
}
效果图: