设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象 p1,设计这两个类的构造函数、析构函数和拷贝构造函数。
#include <iostream>
using namespace std;
class Per
{
string name;
int age;
int *high;
int *wigth;
public:
Per()
{
cout << "Per 无参构造函数" <<endl;
}
Per(string name, int age, int high, int wigth):name(name), age(age), high(new int), wigth(new int)
{
cout << "Per 有参构造函数" <<endl;
}
Per(Per &other)
{
name = other.name;
age = other.age;
high = other.high;
wigth= other.wigth;
high = new int;
*high = *(other.high);
wigth = new int;
*wigth = *(other.wigth);
cout << "Per的拷贝构造函数" << endl;
}
~Per()
{
cout << "释放堆区空间" <<endl;
delete high;
high = nullptr;
delete wigth;
wigth = nullptr;
cout <<"Per的析构函数" <<endl;
}
void set_age(int age);
void show();
void set_p(int d)
{
*wigth = d;
}
};
void Per::set_age(int age)
{
this ->age =age;
}
void Per::show()
{
cout << age <<endl;
cout << high <<endl;
cout << wigth <<endl;
}
class Stu
{
float score;
Per p1;
public:
Stu(string name, int age, int high, int wigth):p1(name, age, high, wigth)
{
cout << "Stu的函构造函数" <<endl;
}
void set_score(float score);
~Stu()
{
cout << "Stu的析构函数" <<endl;
}
Stu(Stu &other)
{
this->p1 = other.p1;
this->score = other.score;
cout << "Stu的拷贝构造函数" <<endl;
}
void set_age( int age);
void show();
void set_p(int p);
};
void Stu::set_age(int age)
{
p1.set_age(age);
}
void Stu::set_score(float score)
{
this ->score = score;
}
void Stu:: set_p(int p)
{
p1.set_p(p);
}
void Stu::show()
{
p1.show();
cout << "score= " <<score <<endl;
}
int main()
{
Stu s1("ZS", 18, 180, 128);
s1.set_score(98.2);
Stu s2 = s1;
s1.set_p(100);
s1.set_age(15);
s1.set_score(97.6);
cout << "s1 = " ;
s1.show();
cout << "s2 =" ;
s2.show();
return 0;
}