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;
}
相关推荐
JienDa1 小时前
JienDa聊PHP:小红书仿站实战深度架构全解析
开发语言·架构·php
执笔论英雄6 小时前
Slime异步原理(单例设计模式)4
开发语言·python·设计模式
止观止7 小时前
C++20 Concepts:让模板错误信息不再“天书”
c++·c++20·编程技巧·模板编程·concepts
e***74957 小时前
Modbus报文详解
服务器·开发语言·php
lly2024067 小时前
ASP 发送电子邮件详解
开发语言
小徐敲java7 小时前
python使用s7协议与plc进行数据通讯(HslCommunication模拟)
开发语言·python
likuolei7 小时前
XSL-FO 软件
java·开发语言·前端·数据库
6***37947 小时前
PHP在电商中的BigCommerce
开发语言·php
Dev7z7 小时前
基于Matlab的多制式条形码识别与图形界面(GUI)系统设计与实现
开发语言·matlab
合作小小程序员小小店7 小时前
桌面开发,在线%信息管理%系统,基于vs2022,c#,winform,sql server数据。
开发语言·数据库·sql·microsoft·c#