C++day3(设计一个Per类,类中包含私有成员:姓名、年龄...)

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

#include 

using namespace std;

class Per
{
private:
    string name;
    int age;
    float *height;      //指针成员
    float *weight;
public:
    //Per提供的无参构造函数
    Per()
    {

    }
    //Per提供的有参构造函数
    Per(string name, int age, float height, float weight):name(name),age(age),height(new float(height)),weight(new float(weight))
    {

    }
    //析构函数
    ~Per()
    {
        delete height;
        height = nullptr;
        delete weight;
        weight = nullptr;
    }
    //深拷贝构造函数
    Per(Per &other)
    {
        this->name = other.name;
        this->age = other.age;
        this->height = new float(*(other.height));
        this->weight = new float(*(other.weight));
    }
    void set_p(float height,float weight)
    {
        *(this->height) = height;
        *(this->weight) = weight;
    }
     void fun();
};

class Stu {
private:
    float score;
    Per p1;

public:
    //Stu提供的无参构造函数
    Stu()
    {

    }
    //Stu提供的有参构造函数
    Stu(float score,Per &p1):score(score),p1(p1)
    {

    }
    //析构函数
    ~Stu()
    {
    }
    void set_p(float height,float weight)
    {
        p1.set_p(height,weight);
    }
    //深拷贝构造函数
    Stu(Stu &other)
    {
        this->score = other.score;
        this->p1 = other.p1;
    }
    void fun();
};

void Per::fun()
{
    cout << "姓名: " << name << endl;
    cout << "年龄: " << age << endl;
    cout << "身高: " << *height << endl;
    cout << "体重: " << *weight << endl;
}

void Stu::fun()
{
    p1.fun();
    cout << "成绩: " << score << endl;
}

int main()
{
    Per p1("xjx", 22, 158.5, 50.2);
    p1.fun();

    Stu s1(100,p1);
    s1.fun();

    Stu s2 = s1;
    s1.fun();

    s1.set_p(180,120);
    s1.fun();
    s2.fun();
    return 0;
}


C++day3(设计一个Per类,类中包含私有成员:姓名、年龄...)_第1张图片

你可能感兴趣的:(c++,开发语言)