#include <iostream>
using namespace std;
class Per
{
friend class Stu;
private:
string name;
int age;
int *ht;
int *we;
public:
Per()
{ cout << "无参构造" << endl; }
//构造函数
Per(string name,int age,int ht,int we):name(name),age(age),ht(new int(ht)),we(new int(we))
{
cout << "Per:: 有参构造" << endl;
}
//拷贝构造
Per(const Per &other):name(other.name),age(other.age),ht(new int(*(other.ht))),we(new int (*(other.we)))//深拷贝
{
cout << "Per:: 拷贝构造" << endl;
}
//拷贝赋值
Per &operator=(const Per &other)
{
if(this != &other)
{
name = other.name;
age = other.age;
ht = new int(*(other.ht));
we = new int(*(other.we));
}
cout << "拷贝赋值" << endl;
return *this;
}
//析构函数
~Per()
{
delete ht;
delete we;
cout << "Per :: 析构函数" << endl;
}
void show()
{
cout << "&this=" << this << endl;
cout << "name = " << name << endl;
cout << "age = " << age << endl;
cout << "ht = " << *ht << endl;
cout << "we = " << *we << endl;
}
};
class Stu
{
private:
int socre;
Per* p1;//嵌套另一个类
public:
Stu()
{
cout << "Stu:: 无参构造" << endl;
}
Stu(int socre,Per p1):socre(socre),p1(new Per(p1))
{
cout << "Stu:: 有参构造函数" << endl;
}
Stu(const Stu &other):socre(other.socre), p1(new Per(*(other.p1)))
{
cout << "Stu :: 拷贝构造" << endl;
}
Stu &operator=(const Stu &other)
{
socre = other.socre;
p1 = other.p1;
cout << "Stu:: 拷贝赋值" << endl;
return *this;
}
~Stu()
{
delete p1;
cout << "Stu:: 析构函数" << endl;
}
void show()
{
cout << "&this=" << this << endl;
cout << "socre=" << socre << endl;
cout << "name=" << p1->name << endl;
cout << "age = " << p1->age << endl;
cout << "ht = " << *(p1->ht) << endl;
cout << "we = " << *(p1->we) << endl;
}
};
int main()
{
Per p1;
Per p2("lisi",18,180,75);
Per p3(p2);
p1 = p3;
cout << "&p1=" << &p1 << endl;
cout << "&p2=" << &p2 << endl;
cout << "&p3=" << &p3 << endl;
p2.show();
p3.show();
p1.show();
Stu s1;
Stu s2(95,p1);
Stu s3(s2);
s1 = s3;
s1.show();
cout << "&s1=" << &s1 << endl;
cout << "&s2=" << &s2 << endl;
cout << "&s3=" << &s3 << endl;
s2.show();
s3.show();
s1.show();
return 0;
}
设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数、拷贝赋值函数。
于 2023-11-07 20:13:20 首次发布