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;
}
相关推荐
我不是8神2 分钟前
序列化与反序列化详解
c++
廋到被风吹走3 分钟前
【Java】【JVM】OOM 原因、定位与解决方案
java·开发语言·jvm
MSTcheng.6 分钟前
【C++STL】map / multimap 保姆级教程:从底层原理到实战应用!
开发语言·c++·stl·map·红黑树
csbysj20208 分钟前
Bootstrap5 按钮组
开发语言
kaikaile19959 分钟前
使用纯MATLAB M函数实现的无刷直流电机控制系统仿真
开发语言·matlab
崇山峻岭之间12 分钟前
Matlab学习记录09
开发语言·学习·matlab
wjs202414 分钟前
Python XML 解析
开发语言
ULTRA??15 分钟前
基于range的函数式编程C++,python比较
c++·python·kotlin·c++20
小白学大数据16 分钟前
Temu 商品历史价格趋势爬虫与分析
开发语言·javascript·爬虫·python
帮帮志18 分钟前
启动phcharm报错:Archived non-system classes are disabled because the java.system.
java·开发语言