#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;
}
运行:
思维导图: