作业要求:
代码:
#include <iostream>using namespace std;class Per
{
private:string name;int age;double *high;double *weight;
public://有参构造函数Per(string n,int a,double h,double w):name(n),age(a),high(new double(h)),weight(new double(w)){cout << "Per实例化对象构造成功" << endl;cout << name << " " << age << " " << *high << " " << *weight << endl;}//析构函数~Per(){delete(high);delete(weight);high = nullptr;weight = nullptr;cout << "Per对象析构成功" << endl;}//拷贝构造函数(深拷贝)Per(const Per &o):name(o.name),age(o.age),high(new double(*(o.high))),weight(new double(*(o.weight))){cout << "Per对象拷贝构造成功" << endl;cout << name << " " << age << " " << *high << " " << *weight << endl;}//显示函数void show(){cout << name << " " << age << " " << *high << " " << *weight << " ";}};class Stu
{
private:double score;Per p1;
public://有参构造函数Stu(double s,string n,int a,double h,double w):score(s),p1(n,a,h,w){cout << "Stu实例化对象构造成功" << endl;p1.show();cout << score << endl;}//析构函数~Stu(){cout << "Stu对象析构成功" << endl;}//拷贝构造函数(浅拷贝)Stu(const Stu &o):score(o.score),p1(o.p1){cout << "Stu对象拷贝构造成功" << endl;p1.show();cout << score << endl;}
};int main()
{cout << "请输入姓名、年龄、身高、体重、成绩:" << endl;string name;int age;double high,weight,score;cin >> name >> age >> high >> weight >> score;Stu s1(score,name,age,high,weight);cout << "------------------------------" << endl;cout << "请输入姓名、年龄、身高、体重:" << endl;cin >> name >> age >> high >> weight;Per p1(name,age,high,weight);cout << "------------------------------" << endl;Stu s2(s1);cout << "------------------------------" << endl;Per p2(p1);return 0;
}
代码运行效果图:
思维导图:
模拟面试: