当前位置: 首页 > article >正文

2024.08.30

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

#include <iostream>
using namespace std;
class Per
{
private:
    string name;
    int age;
    int *high;
    int *weight;

public:
    // 构造函数
    Per()
    {
        high = nullptr;
        weight = nullptr;
        cout << "无参构造函数" << endl;
    }
    Per(string n, int a, int h, int w) : name(n), age(a), high(new int(h)), weight(new int(w))
    {
        cout << "有参构造函数" << endl;
    }

    // 深拷贝
    Per(const Per &other) : name(other.name), age(other.age), high(new int(*other.high)), weight(new int(*other.weight))
    {
        cout << "拷贝构造函数执行" << endl;
    }
    // 析构函数
    ~Per()
    {
        
        delete high;
        delete weight;
        high = nullptr;
        weight = nullptr;
        cout << "析构函数执行" << endl;
    }
    void show()
    {
        cout << "name:" << name << endl;
        cout << "age:" << age << endl;
        cout << "high:" << *high << endl;
        cout << "weight:" << *weight << endl;
    }
};
class Stu
{
private:
    float score;
    Per p1;

public:
    // 构造函数
    Stu()
    {
        
        cout << "无参函数执行" << endl;
    }
    Stu(float s , string name , int age , int high , int weigh):score(s),p1(name,age,high,weigh)
    {
        cout << "有参构造函数执行" << endl;
    }
    // 拷贝构造函数
    Stu(const Stu &other):score(other.score),p1(other.p1)
    {
        cout << "拷贝构造函数执行" << endl;
    }
    // 析构函数
    ~Stu()
    {
        
        cout << "析构函数执行" << endl;
    }

    void show()
    {
        cout << "score:" << score << endl;
       
        p1.show();
       
    }
};
int main()
{
    Per p1;                      // 无参构造函数
    Per p2("张三", 18, 170, 70); // 有参构造函数
    Per p3(p2);                  // 拷贝构造函数
    p3.show();

    Per p4 = p3;

    cout << "===================" << endl;

    Stu s1;
    Stu s2(100,"李四",18,170,70);
    Stu s3(s2);
    s3.show();
    return 0;
}


http://www.kler.cn/news/283953.html

相关文章:

  • JVM面试(一)什么是虚拟机?什么是class文件?
  • ASP.NET Core6.0-wwwroot文件夹无法访问解决方法
  • docker基本使用及常见问题
  • github怎么删除项目
  • 使用dom4j.jar包读取xml内的标签等信息
  • 高级java每日一道面试题-2024年8月30日-基础篇-你对泛型了解多少?
  • 私人诊所|基于SprinBoot+vue的私人诊所管理系统(源码+数据库+文档)
  • STM32——看门狗(独立/窗口)
  • python删除一个函数 ast
  • 如何将FMEA整合到组织的质量管理体系中?
  • 百度:未来or现在 顾此失彼?
  • 如何利用智能文档处理技术,搭建供应链金融智能审单系统?
  • 《深入浅出WPF》读书笔记.9Command系统
  • 人工智能的可解释性(XAI) | 使用LIME
  • NeRF笔记
  • 发布app到ios
  • 【网络】NAT、代理服务、内网穿透
  • Substance 3D Stager for Mac/Win:高效三维场景设计利器
  • AI大模型编写多线程并发框架(六十三):监听器优化·下
  • Goolge earth studio 进阶3——路径创建与编辑
  • 15行为型设计模式——责任链模式
  • NCNN入门之编译与安装
  • Redis的内存淘汰策略- volatile-lru
  • Linux命令行更换yum源repo为阿里源-centos7
  • 【分布式注册中心】NACOS_2.3.0部署与实战
  • DPR:一种用于开放与问答任务的检索方法
  • 暴搜、深搜、回溯算法题集
  • AI如何改变科学与数学领域:陶哲轩演讲解析
  • SpringBoot+redis+aop处理黑白名单
  • PHP伪协议总结