- 設(shè)計一個Per類,類中包含私有成員:姓名、年齡、指針成員身高、體重,再設(shè)計一個Stu類,類中包含私有成員:成績、Per類對象 p1,設(shè)計這兩個類的構(gòu)造函數(shù)、析構(gòu)函數(shù)和拷貝構(gòu)造函數(shù)。
#include <iostream>using namespace std;
class Per
{string name;int age;int *hight;int *weight;
public:void my_set(string name,int age){this-> name = name;this-> age = age;}void show(){cout <<"名字為:" << name << ' ' << "成績?yōu)?" << age << ' ';cout << "身高為:" << *hight << ' ' << "體重為:" << *weight << endl;}Per(int *h,int *w):hight(new int),weight(new int){hight=h;weight=w;cout << "這是Per的構(gòu)造函數(shù)" << endl;}Per(Per &other){int *hi=new int;int *we=new int;*hi = *(other.hight);*we = *(other.weight);cout << "這是Per的拷貝構(gòu)造函數(shù)" << endl;}~Per(){cout << "這是Per的解析函數(shù)" << endl;delete hight;delete weight;hight = nullptr;weight = nullptr;}
};class Stu
{int score;
public:Per p1;void set_stu(int score){this->score=score;}void show(){cout << "成績?yōu)?" << score << endl;}Stu(int *hight,int *weight):p1(hight,weight){cout << "這是Stu的構(gòu)造函數(shù)" << endl;}Stu(Stu &other):p1(other.p1){this ->score = other.score;p1=other.p1;cout << "這是Stu的拷貝構(gòu)造函數(shù)" << endl;}~Stu(){cout << "這是Stu的解析函數(shù)" <<endl;p1.~Per();}};int main()
{int *hight=new int;*hight = 183;int *weight=new int;*weight = 120;Stu s1(hight,weight);s1.p1.my_set("張三",18);s1.p1.show();s1.set_stu(89);s1.show();*hight = 180;*weight = 110;Stu s2(hight,weight);s2.p1.my_set("李四",20);s2.p1.show();s2.set_stu(90);s2.show();return 0;
}
