c++ day3

设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。

#include 

using namespace std;
class Per
{
private:
    string name;
    int age;
    double * hight;
    double * weight;
public:
    Per(string name,int age,int hight,double weight):name(name),age(age),hight(new double(hight)),weight(new double(weight))
    {
        cout << "per::构造函数" << endl;
    }
    ~Per()
    {
        //cout << this << endl;
        delete hight;
        delete weight;
        hight=nullptr;
        weight=nullptr;
        cout << "per::析构函数" << endl;
    }
    Per(const Per &other):name(other.name),age(other.age),hight(new double(*(other.hight))),weight(new double(*(other.weight)))
    {
        cout << "per::拷贝构造函数" << endl;

    }
    void show()
    {
        cout << "name=" << name << endl;
        cout << "age="  << age  << endl;
        cout << "身高="  << *hight << endl;
        cout << "体重="  << *weight << endl;
    }
};
class Stu
{
private:
    double score;
    Per p1;
public:
    Stu(double score,string name,int age,int hight,double weight):score(score),p1(name,age,hight,weight)
    {
        cout << "Stu::构造函数" << endl;
    }
    ~Stu()
    {
        cout << "Stu析构函数" << endl;
       // cout << this << endl;
    }
    Stu(const Stu &other1):score(other1.score),p1(other1.p1)
    {
        cout << "Stu::拷贝构造函数" << endl;
    }
    void show()
    {
        cout << "score=" << score << endl;
        p1.show();
    }
};
int main()
{
    Stu s1(99,"张",18,190,65);
    Stu s2(s1);
    s1.show();
    Per p1("张",18,190,65);
    Per p2(p1);
    p1.show();

    return 0;
}

c++ day3_第1张图片c++ day3_第2张图片

你可能感兴趣的:(c++)