C++中的特殊成员函数

1思维导图

cpp 复制代码
#include <iostream>

using namespace std;

//设计一个per类
class Per
{
private:
    string name;
    int age;
    double *weight;
    double *high;
public:
    //无参构造函数
    Per()
    {
        weight = nullptr;
        high = nullptr;
        cout << "Per:: 无参构造函数" << endl;
    }
    //有参构造函数
    Per(string name,int age,double weight,double high):name(name),age(age),weight(new double(weight)),high(new double(high))
    {
        cout << "Per::有参构造函数" << endl;
    }

    //拷贝构造函数
    Per(const Per &other):name(other.name),age(other.age),weight(new double(*other.weight)),high(new double(*other.high))
    {
        cout << "拷贝构造函数" << endl;
    }
    //拷贝赋值函数
    Per& operator=(const Per &other)
    {
        if(this!=&other)
        {
            name = other.name;
            age = other.age;
            weight = new double(*other.weight);
            high = new double(*other.high);
        }
        cout << "Per::拷贝赋值函数" << endl;
        return *this;
    }
    //析构函数
    ~Per()
    {
        delete weight;
        delete high;
        weight = nullptr;
        high = nullptr;
        cout << "Per::析构函数" << endl;
    }
    void show()
    {
        cout << "name = " << name << endl;
        cout << "age = " << age << endl;
        cout << "high = " << *high << endl;
        cout << "weight = " << *weight << endl;
    }
};

//Stu类
class Stu
{
private:
    double score;
    Per p1;
public:
    Stu()
    {
        cout << "Stu::无参构造函数" << endl;
    }
    Stu(double score,string name ,int age,double wight,double high):score(score),p1(name,age,wight,high)
    {
        cout << "Stu::有参构造函数" << endl;
    }
    Stu& operator=(const Stu &other)
    {
        if(this!=&other)
        {
            score = other.score;
            p1 = other.p1;
        }
        cout << "Stu::拷贝赋值函数" << endl;
        return *this;
    }
    Stu(const Stu &other):score(other.score),p1(other.p1)
    {
        cout << "Stu::拷贝构造函数" << endl;
    }
    ~Stu()
    {
        cout << "Stu::析构函数" << endl;
    }
    void show()
    {
        p1.show();
        cout << "Stu::score = " << score << endl;
    }
};

int main()
{

    Stu s1;
    Stu s2(99,"张三",18,200,160);
    s1 =s2;
    s1.show();
    Stu s3 = s1;
    return 0;
}
相关推荐
张人玉几秒前
C# 串口通讯中 SerialPort 类的关键参数和使用方法
开发语言·c#·串口通讯
白山云北诗11 分钟前
网站被攻击了怎么办?如何进行DDoS防御?
开发语言·网络安全·php·ddos·防ddos·防cc
程序定小飞33 分钟前
基于springboot的作业管理系统设计与实现
java·开发语言·spring boot·后端·spring
ceclar12335 分钟前
C++线程操作
c++
Jonathan Star38 分钟前
NestJS 是基于 Node.js 的渐进式后端框架,核心特点包括 **依赖注入、模块化架构、装饰器驱动、TypeScript 优先、与主流工具集成** 等
开发语言·javascript·node.js
晓庆的故事簿39 分钟前
windows下载和使用minio,结合java和vue上传文件
java·开发语言
2301_807997381 小时前
代码随想录-day30
数据结构·c++·算法·leetcode
猫头虎1 小时前
永久免费白嫖多个域名,一键托管Cloudflare,免费申请SSL加密证书,轻松建站、搭建线路伪装
服务器·开发语言·网络·数据库·python·网络协议·ssl
咔咔咔的1 小时前
3607. 电网维护
c++
无敌最俊朗@2 小时前
C++后端总览
开发语言