华清远见作业第三十四天——C++(第三天)

思维导图:

题目:

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

代码:

#include 

using namespace std;
class Per
{
private:
    string name;
    int age;
    int *heigh;
    int *weith;
public:
    //构造函数
    Per()
    {
        cout << "Per::无参构造函数" << endl;
        cout << this << endl;
    }
    Per(string name,int age,int heigh,int weith):name(name),age(age),heigh(new int(heigh)),weith(new int(weith))
    {
        cout << "Per::有参构造函数" << endl;
        cout << this << endl;
    }
    //析构函数
    ~Per()
    {
        cout << "Per::析构函数" << endl;
        cout << this << endl;
    }
    //拷贝函数
    Per(const Per &other):name(other.name),age(other.age),heigh(new int(*other.heigh)), weith(new int(*other.weith))
    {
        cout << "Stu::拷贝构造函数" << endl;
        cout << this << endl;
    }
    void show()
    {
        cout << "名字=" << name << endl;
        cout << "年龄=" << age << endl;
        cout << "身高=" << *heigh << endl;
        cout << "体重=" << *weith << endl;
    }
};
class Stu
{
private:
    int score;
    Per p1;
public:
    //构造函数
    Stu()
    {
        cout << "Stu::无参构造函数" << endl;
        cout << this << endl;
    }
    Stu(int score,string name,int age,int heigh,int weith):score(score),p1(name,age,heigh,weith)
    {
        cout << "Stu::有参构造函数" << endl;
        cout << this << endl;
    }
    //析构函数
    ~Stu()
    {
        cout << "Stu::析构函数" << endl;
        cout << this << endl;
    }
    //拷贝函数
    Stu(const Stu &other):score(other.score),p1(other.p1)
    {
        cout << "Stu::拷贝构造函数" << endl;
        cout << this << endl;
    }
    void show()
    {
        cout << "成绩=" << score << endl;
        cout << this << endl;
        p1.show();
    }
};
int main()
{

    Stu s1;
    Stu s2(88,"sss",22,123,32);
    cout << "&s1=" << &s1 << endl;
    cout << "&s2=" << &s2 << endl;
    s2.show();
    Stu s3=s2;
    s3.show();
    cout << "&s3=" << &s3 << endl;
    return 0;
}

运行效果:

华清远见作业第三十四天——C++(第三天)_第1张图片

你可能感兴趣的:(华清远见作业,c++)