zoukankan      html  css  js  c++  java
  • 类的构造、移动、赋值函数示例

    #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;
    }
  • 相关阅读:
    abstract和virtual
    vue中 关于$emit的用法
    babel简介
    vue脚手架的使用
    RAM和ROM
    判断匿名类是否继承父类
    ABP应用层——参数有效性验证
    vue-devtools的安装与使用
    JavaScript中Object.keys用法
    vue中created、mounted、 computed,watch,method 等方法整理
  • 原文地址:https://www.cnblogs.com/qiumingcheng/p/15483559.html
Copyright © 2011-2022 走看看