1.26 C++ day3

思维导图

1.26 C++ day3_第1张图片

作业:

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

代码

#include 

using namespace std;

class Per//封装一个Per类
{
private://表示私有属性
    string name;//成员:姓名
    int age;//成员:年龄
    int *height;//指针成员:身高
    double *weight;//指针成员:体重
public:
    //无参构造函数
    Per()
    {
        cout << "Per::无参构造函数" << endl;
    }
    //有参构造函数
    Per(string name,int age,int height,double weight):name(name),age(age),height(new int(height)),weight(new double(weight))
    {                                                 //初始化列表
        cout << "Per::有参构造函数" << endl;
    }
    //析构函数
    ~Per()
    {
        cout << "Per::析构函数" << endl;
        delete height;//手动释放指针成员height所申请的堆区空间
        delete weight;//手动释放指针成员weight所申请的堆区空间
    }
    //拷贝构造函数
    Per(const Per &other):name(other.name),age(other.age)//初始化列表
    {
        height=new int(*other.height);//拷贝身高
        weight=new double(*other.weight);//拷贝体重
        cout << "Per::拷贝构造函数" << endl;
    }
    //把成员都输出在终端上
    void show()
    {
        cout << "name:" << name << ",";
        cout << "age:" << age << ",";
        cout << "height:" << *height << ",";
        cout << "weight:" << *weight << endl;
    }
};
class Stu//封装一个Stu类
{
private:
    double score;//成员:成绩
    Per p1;//成员:Per类对象p1
public:
    //无参构造函数
    Stu()
    {
        cout << "Stu::无参构造函数" << endl;
    }
    //有参构造函数
    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;
    }
    //拷贝构造函数
    Stu(const Stu &other):score(other.score),p1(other.p1)
    {
        cout << "Stu::拷贝构造函数" << endl;
    }
    void show()
    {
        cout << "score:" << ",";
        p1.show();
    }
};

int main()
{
    Per p;//用Per实例化一个对象p
    Per p2("张三",18,180,85.5);//p2=Per("张三",18,180,85.5);
    cout << "p2:" ;//提示是p2
    p2.show();//输出p2
    Per p3=p2;//p3.Per(p2);
    cout << "p3:" ;//提示是p3
    p3.show();//输出p3
    Stu s1;//用Stu实例化一个对象s1
    Stu s2(99.99,"李四",19,186,77.7);//s2=Stu(99.99,"李四",19,186,77.7);
    cout << "s2:" ;//提示是s2
    s2.show();//输出s2
    Stu s3=s2;//s3.Stu(s2);
    cout << "s3:" ;//提示是s3
    s3.show();//输出s3
    return 0;
}

结果

1.26 C++ day3_第2张图片

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