设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数、拷贝赋值函数。
- #include
-
- using namespace std;
- class Per
- {
- friend class Stu;
- private:
- string name;
- int age;
- int *hig;
- int *wig;
- public:
- Per(string name,int age,int* hig,int* wig):name(name),age(age),hig(new int(*hig)),wig(new int(*wig))
- {
- cout << "有参构造函数" << endl;
- }
- ~Per()
- {
- delete hig;
- delete wig;
- hig = nullptr;
- wig = nullptr;
- cout << "析构函数" << endl;
- }
- Per(const Per &other):name(other.name),age(other.age),hig(new int(*(other.hig))),wig(new int(*(other.wig)))
- {
- cout << "拷贝构造函数" << endl;
- }
- Per & operator=(const Per &p)
- {
- name = p.name;
- age = p.age;
- hig = new int(*(p.hig));
- wig = new int(*(p.wig));
- cout << "拷贝赋值函数" << endl;
- return *this;
- }
- void show()
- {
- cout << name << " " << age << " " << *hig << " " << *wig << endl;
- }
- };
- class Stu
- {
- private:
- int soc;
- Per p1;
- public:
-
- Stu(int soc,Per &p):soc(soc),p1(p)
- {
- cout << "stu有参构造函数" << endl;
- }
- ~Stu()
- {
- cout << "stu析构函数" << endl;
- }
- Stu(const Stu &ss):soc(ss.soc),p1(ss.p1)
- {
- cout<< "stu拷贝构造函数" << endl;
- }
- Stu & operator=(const Stu & ss)
- {
- soc = ss.soc;
- p1 = ss.p1;
- cout << "stu拷贝赋值函数" << endl;
- return *this;
- }
- void show()
- {
- cout << soc << " " << p1.name << " " << p1.age << " " << *(p1.hig) << " " << *(p1.wig) << endl;
- }
- };
- int main()
- {
- int a = 105;
- int b = 188;
- Per p("ko",18,&b,&a);//有参构造函数
- Per pp(p);//拷贝构造函数
- pp = p; //拷贝赋值函数
- pp.show();
- Stu s1(99,pp);//stu有参构造函数
- Stu s2(s1);//stu拷贝构造函数
- Stu s3(89,p);
- s3 = s1;//stu拷贝赋值函数
- s3.show();
- return 0;
- }