今日任务
1> 思维导图
2> 设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。
代码:
#include <iostream>
using namespace std;
/*
* 设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,
* 再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,
* 设计这两个类的构造函数、析构函数和拷贝构造函数。
*/
class Per
{
private:
string name;
int age;
int *height;
int *weight;
public:
Per() {
cout << "Per::无参构造" <<endl;
}
Per(string name,int age,int height,int weight):name(name),age(age),height(new int(height)),weight(new int(weight)){
cout << "Per::有参构造" <<endl;
}
~Per(){
delete height;
delete weight;
cout << "Per::析构函数" <<endl;
}
Per(const Per &per):name(per.name),age(per.age),height(new int(*per.height)),weight(new int(*per.weight)){
cout << "Per::拷贝构造函数" <<endl;
}
void show(){
cout << "per_info: name" << name << ";name" << age << ";height" << *height << ";weight" << *weight <<endl;
}
};
class Stu
{
private:
int score;
Per p1;
public:
Stu() {
cout << "Stu::无参构造" <<endl;
}
Stu(int score,Per p1):score(score),p1(p1){
cout << "Stu::有参构造" <<endl;
}
~Stu(){
cout << "Stu::析构函数" <<endl;
}
Stu(Stu &stu):score(stu.score),p1(stu.p1){
cout << "Stu::拷贝构造函数" <<endl;
}
void show(){
cout << "stu_info: score" << score << "p1";
p1.show();
}
};
int main()
{
Per p1;
Per p2("张三",19,182,75);
Per p3=p2;
//p1.show();
p2.show();
p3.show();
cout << "------------" <<endl;
Stu s1;
Stu s2(99,p2);
Stu s3=s2;
//s1.show();
s2.show();
s3.show();
cout << "------------" <<endl;
return 0;
}
运行结果:一开始的时候出现了个问题,就是我调用p1.show()和s1.show()的话输出会遗漏,结果如下下图,我想输出一个随机值也不会影响其他语句的输出啊,不知道为什么
今日思维导图