C++学习day3

目录

作业:

[1> 思维导图](#1> 思维导图)

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

效果图:


作业:

1> 思维导图

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

cpp 复制代码
#include <iostream>

using namespace std;
//设计一个per类和stu类
class Per
{
private://私有的
    string name;//姓名
    int age;//年龄
    double *hight;//身高
    double *weight;//体重
public:
    //构造函数
    Per(string n,int a,double h,double w):name(n),age(a),hight(new double(h)),weight(new double(w))
    {
        cout << "Per::有参构造函数" << endl;

    }
    string GetName()const
    {
            return name;
        }

        int GetAge() const
        {
            return age;
        }

        double GetHight() const
        {
            return *hight;
        }

        double GetWeight() const
        {
            return *weight;
        }

    void show()
    {
        cout << "姓名:" << name << endl;
        cout << "年龄:" << age << endl;
        cout << "身高:" << *hight << endl;
        cout << "体重:" << *weight << endl;
    }
    //析构函数
    ~Per()
    {
        cout << "Per::析构函数" << endl;
        delete hight;
        delete weight;

    }


};
class Stu
{
private:
    int score;//成绩
     Per p1;//学生信息
public:
     //构造函数
     Stu(int s,string n,int a,double h,double w): score(s), p1(n,a,h,w)
     {
         cout << "Stu:: 有参构造函数" << endl;
     }
    void show()
    {
        cout << "成绩:"<< score << endl;
        p1.show();
    }
    //拷贝构造函数
    Stu(const Stu &other):score(other.score),p1(other.p1)
    {
        cout << "Stu::拷贝构造函数" <<endl;

    }
    Stu& operator=(const Stu& other)
    {
        if (this == &other)
            return *this;

        score = other.score;
        p1 = Per(other.p1.GetName(), other.p1.GetAge(), other.p1.GetHight(), other.p1.GetWeight());

        return *this;
    }


    //析构函数
    ~Stu()
    {
        cout << "Stu:: 析构函数" << endl;

    }

};

int main()
{
    Stu S1(100,"zhangsan",23,180.7,100.98);//有参构造函数
    S1.show();
    Stu S2(S1);//拷贝构造函数


    return 0;
}

效果图:

相关推荐
不想写代码的星星20 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus3 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_6 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛8 天前
delete又未完全delete
c++
端平入洛9 天前
auto有时不auto
c++
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
西岸行者9 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习