C++ day3

1.思维导图

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

复制代码
#include <iostream>

using namespace std;

class Per
{
private:
    string name;
    int age;
    double *height;
    double *weight;
public:
    //无参构造函数
    Per()
    {
        cout << "Per::无参构造函数" << endl;
    }
    //有参构造函数
    Per(string name,int age,double height,double weight):name(name),age(age),height(new double(height)),weight(new double(weight))
    {
        cout << "Per::有参构造函数" << endl;
    }

    //浅拷贝构造函数
//    Per(const Per &other):name(other.name),age(other.age),height(other.height),weight(other.weight)
//    {
//        cout << "Per::浅拷贝" << endl;
//    }
    //深拷贝构造函数
    Per(const Per &other):name(other.name),age(other.age),height(new double(*(other.height))),weight(new double(*(other.weight)))
    {
        cout << "Per::深拷贝" << endl;
    }
    //析构函数
    ~Per()
    {
        cout << "Per::析构函数" << endl;
    }

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

class Stu
{
private:
    int score;
    Per p1;
public:
    //无参构造函数
    Stu()
    {
        cout << "Stu::无参构造函数" << endl;
    }
    //有参构造函数
    Stu(int score,Per p1):score(score),p1(p1)
    {
        cout << "Stu::有参构造函数" << endl;
    }
    //析构函数
    ~Stu()
    {
        cout << "Stu::析构函数" << endl;
    }
    void show()
    {
        cout << "成绩:" << score << endl;
        p1.show();
    }
};
int main()
{
    Per r1();    //自动调用无参构造函数
    Per r2("张三",23,178,120);     //自动调用有参构造函数
    Per r3=r2;
    Stu s1;
    Stu s2(88,r2);
    s2.show();

    return 0;
}
相关推荐
旖旎夜光11 小时前
LeetCode 852:山脉数组的峰顶索引(二分查找) —— 题解
数据结构·c++·算法·leetcode·二分查找
程与留11 小时前
05_Qt 核心模块概览——Qt Core、Gui、Widgets、Quick 的职责划分
c++·qt
CRMEB定制开发11 小时前
2026年最值得推荐的10大开源商城系统盘点
开发语言·人工智能·开源·商城系统·小程序商城
buhuizhiyuci11 小时前
【QT-百日筑基篇】修真世界摸爬滚打多年,终于黄天不负有心人,突破炼器中期——常用控件QWight的属性
开发语言·c++·qt·gui·图形化
Littlehero_12113 小时前
QT自定义控件之热换站系统(源码开源)
开发语言·qt
meilindehuzi_a13 小时前
Python 基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
caimouse13 小时前
ReactOS 窗口系统分析(5):可见区域与窗口 DC — vis.c + windc.c
c语言·开发语言
OPEN-F13 小时前
Python进阶教程:装饰器与生成器深入
开发语言·python
千里码aicood14 小时前
基于Python的电商数据采集系统(大数据+爬虫)
开发语言·python
_Narcissus_15 小时前
动态规划初探(含完整代码实现)
c语言·数据结构·c++·算法·动态规划·背包问题·最短路径