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;
}
相关推荐
汉克老师5 小时前
CSP-J 2026 第二轮入门组真题解析(第一题 、旅游)
c++·csp-j·信息学竞赛·小学生学c++
xiaoye-duck6 小时前
《C++ 项目:手写大模型接入 SDK》Gemini接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
nice_lcj5208 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河669 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
UIU11410 小时前
P1481 魔族密码
c++·算法·动态规划
nice_lcj52013 小时前
ThreadLocal 入门:它是怎么隔离数据的、为什么会导致内存泄漏
java·开发语言·后端·面试·并发编程·内存泄漏·threadlocal
紧跟先前的步伐13 小时前
Go AI Agent 实战 28|Agent 的预算、超时与停止条件
开发语言·人工智能·后端·ai·golang
bksczm14 小时前
InnoDB 行格式详解:DYNAMIC / COMPACT / COMPRESSED / REDUNDANT
java·开发语言·数据库
春涧草茶15 小时前
慢就是快16-1协程
开发语言·前端·python
Dovis(誓平步青云)15 小时前
启元 T1 Pro 人机相声搭档:语音-触摸双通道的启元机器人节奏引擎设计
开发语言·前端·javascript·microsoft·交互