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;
}
相关推荐
踏着七彩祥云的小丑17 分钟前
Go学习第8天:接口 + 泛型 + 错误处理
开发语言·学习·golang·go
聆风吟º19 分钟前
Python基础数据类型(一):数字类型
开发语言·python·float·int·bool·数字类型
laplaya19 分钟前
C++大型项目组件通信与依赖管理实践
c++·log4j·apache
春栀怡铃声21 分钟前
【C++修仙录03】进阶篇:多态
c++
小灰灰搞电子27 分钟前
C++ boost::container 详解:高性能容器库完全指南
开发语言·c++·boost
Y_Bk29 分钟前
第十七届蓝桥杯C/C++A组省赛
c语言·数据结构·c++·算法·蓝桥杯
Brilliantwxx29 分钟前
【C++】 C++11 知识点梳理(上)
开发语言·c++
飞天狗11130 分钟前
零基础JavaWeb入门——第4课:表单处理 —— 浏览器怎么把数据发给服务器
java·开发语言·前端·后端·servlet
多彩电脑36 分钟前
向AIDE(安卓设备上的Android Studio)导入aar库
android·java·开发语言·androidx
江屿风1 小时前
C++图论基础单源最短路-常规版dijkstra算法/堆优化版dijkstra算法/bellman-ford 算法/spfa 算法流食般投喂
开发语言·c++·笔记·算法·图论