设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。
#include <iostream>
using namespace std;class Per
{string name;int age;int *height;int *weight;
public://有参构造函数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(){cout << "Per无参构造函数" << endl;}//深拷贝构造函数Per(Per &other){this->name = other.name;this->age = other.age;height = new int(*(other.height));weight = new int(*(other.weight));cout << "Per拷贝构造函数" << endl;}//析构函数~Per(){delete height;delete weight;cout << "Per析构函数" << endl;}void set_msg(int height,int weight){*(this->height) = height;*(this->weight) = weight;}void fun();
};class Stu
{float score;Per p1;
public://有参构造函数Stu(string name,int age,int height,int weight,float score):score(score),p1(name,age,height,weight){cout << "Stu有参构造函数" << endl;}//无参构造函数Stu(){cout << "Stu无参构造函数" << endl;}//深拷贝构造函数Stu(Stu &other){this->p1 = other.p1;this->score = other.score;}//析构函数~Stu(){cout << "Stu析构函数" << endl;}void set_msg(int height,int weight){p1.set_msg(height,weight);}void fun();
};int main()
{Stu student_1("zhangsan",18,180,150,95);// student_1.fun();Stu student_2 = student_1;// student_2.fun();student_1.set_msg(150,100);student_1.fun();student_2.fun();return 0;
}void Per::fun()
{cout << name << " ";cout << age << " ";cout << *height << " ";cout << *weight << " ";
}
void Stu::fun()
{p1.fun();cout << score << endl;
}
类的基础概念整理