#include <iostream>using namespace std;
class Per
{
private:string name;int age;double *height;double *weigh;
public://無參構造Per(){cout << "Per::無參構造" << endl;}//有參構造Per(string name,int age,double height,double weigh):name(name),age(age),height(new double(height)),weigh(new double(weigh)){cout << "Per::無參構造" << endl;}//析構函數~Per(){cout << "Per::析構函數" << endl;//手動釋放指針成員申請的空間delete(height);delete(weigh);}void show(){cout << "name=" << name << " " << "age=" << age << " " << "height=" << *height << " " << "weigh=" << *weigh << endl;}
};class Stu
{
private:int score;Per p1;
public://無參構造Stu(){cout << "Stu::無參構造" << endl;}//有參構造// Stu(int score,string name,int age):score(score),p1(name,age)Stu(double score,string name,int age,int height,double weight):score(score),p1(name,age,height,weight){cout << "Stu::有參構造" << endl;}//析構函數~Stu(){cout << "Stu::析構函數" << endl;}void show(){cout << "score=" << score << " ";p1.show();}
};int main()
{Per s1;//調用無參構造Per s2("zhangsan",18,180,150);//調用有參構造s2.show();cout << "-----------------------------------" << endl;Stu s3;// Stu s4(99,"zhangsan",18);Stu s4(99,"lisi",18,170,99);s4.show();return 0;
}
運行:
思維導圖: