• 类的构造、移动、赋值函数示例


    #include <iostream>
    using namespace std;

    class Teacher {
       public:
        int id;
        int* studentIds{nullptr};
        int count;

       public:
        Teacher(int id, int count) {
            this->id = id;
            this->count = count;
            this->studentIds = new int[count];
        }

        Teacher(Teacher&& other) {
            this->id = other.id;
            this->count = other.count;
            this->studentIds = other.studentIds;
            other.studentIds = nullptr;
        }

        // copy构造函数尽量不给出实现,如果不给出,因为提供了移动copy,所以这个函数是不允许调用的
        // Teacher(Teacher& other) {
        //     this->id = id;
        //     this->count = count;
        //     this->studentIds = other.studentIds; //这里简单这么实现,通常需要深copy,否则可能出现内存被重复释放的问题
        // }

        Teacher& operator=(Teacher&& other) {
            if (this->studentIds) {
                delete this->studentIds;
            }
      this->id = other.id;
           this->count = other.count;
           this->studentIds = other.studentIds;
        }

        // 这个函数尽量不提供,如果需要提供,则需要深copy,因为出现了移动赋值,如果不提供改函数,该函数是不允许使用的
        // Teacher& operator=(Teacher& other) {

        // }
        ~Teacher() {
            if (this->studentIds) {
                delete this->studentIds;
                this->studentIds = nullptr;
            }
        }
    };

    Teacher GetTeacher() {  // 借助了移动copy构造函数的能力,相当于返回了局部变量
        Teacher t(1, 4);
        for (int i = 0; i < t.count; i++) {
            t.studentIds[i] = i;
        }
        return t;
    }

    int main(int argc, char const* argv[]) {
        Teacher p = GetTeacher();

        cout << p.id << " " << p.count << endl;
        for (int i = 0; i < p.count; i++) {
            cout << p.studentIds[i] << " ";
        }
        cout << endl;
        return 0;
    }
  • 相关阅读:
    对象的引用
    查询各个商品分类中各有多少商品的SQL语句
    将TP引擎改为smarty引擎
    图片预加载
    js中接口的声明与实现
    判断对象是否是某个类的实例
    判断变量是否为json对象
    Python 爬取淘宝商品数据挖掘分析实战
    Python 爬取淘宝商品数据挖掘分析实战
    扫盲丨关于区块链你需要了解的所有概念
  • 原文地址:https://www.cnblogs.com/qiumingcheng/p/15483559.html
Copyright © 2020-2023  润新知