Skip to content

构造.h

c
#ifndef MY_CLASS_H
#define MY_CLASS_H

#include <string.h>
#include <iostream>
class MyClass
{
public:
    // 普通构造函数,动态分配指针,注意new和delete配套使用
    MyClass(const char *name, const std::string id)
    {
        this->name = new char[strlen(name) + 1];
        strcpy(this->name, name);
        this->id = id;
        std::cout << "普通构造" << std::endl;
    }

    // 拷贝构造函数,动态分配指针
    MyClass(MyClass &obj)
    {
        this->name = new char[strlen(obj.name) + 1];
        strcpy(this->name, obj.name);
        this->id = obj.id;
        std::cout << "拷贝构造" << std::endl;
    }

    // 拷贝赋值运算符,动态分配指针,注意删除原空间
    MyClass &operator=(MyClass &obj)
    {
        if (this != &obj)
        {
            delete[] this->name;
            this->name = new char[strlen(obj.name) + 1];
            strcpy(this->name, obj.name);
            this->id = obj.id;
        }
        std::cout << "拷贝赋值" << std::endl;
        return *this;
    }

    // 移动构造函数,指向右值对象空间,销毁右值(后续不可用)
    MyClass(MyClass &&obj)
    {
        this->name = obj.name;
        this->id = obj.id;
        obj.name = nullptr;
        std::cout << "移动构造" << std::endl;
    }

    // 移动赋值运算符,销毁原指针空间,指向右值指针空间,销毁原空间
    MyClass &operator=(MyClass &&obj)
    {
        if (this != &obj)
        {
            delete[] this->name;
            this->name = obj.name;
            this->id = obj.id;
            obj.name = nullptr;
        }
        std::cout << "移动赋值" << std::endl;
        return *this;
    }

    // 析构函数,销毁指针
    ~MyClass()
    {
        if (name != nullptr)
        {
            delete[] name;
        }
    }

public:
    // 存在指针属性
    char *name;
    std::string id;
};

#endif // MY_CLASS_H

main.cpp

c
#include <iostream>
#include "my_class.hpp"
#include <string.h>

int main()
{
    // 普通构造
    MyClass c1("he", "11");
    std::cout << "c1.name" << c1.name << "," << "c1.id" << c1.id << std::endl;
    // 将c1转移给c2,移动构造
    MyClass c2(std::move(c1));
    std::cout << "c2.name" << c2.name << "," << "c2.id" << c2.id << std::endl;
    // c1被转移,c1的成员变量被置空
    // std::cout << "c1.name" << c1.name << "," << "c1.id" << c1.id << std::endl;
    // 移动构造(c3对象不存在,触发构造)
    MyClass c3 = std::move(MyClass("q", "k"));
    std::cout << "c3.name" << c3.name << "," << "c3.id" << c3.id << std::endl;
    // 移动赋值(c2对象存在,触发移动赋值)
    c2 = std::move(c3);
    std::cout << "c2.name" << c2.name << "," << "c2.id" << c2.id << std::endl;
    // 拷贝构造
    MyClass c4(c2);
    std::cout << "c4.name" << c4.name << "," << "c4.id" << c4.id << std::endl;
    // 拷贝赋值
    c4 = c2;
    std::cout << "c4.name" << c4.name << "," << "c4.id" << c4.id << std::endl;
    return 0;
}

image-20250611175259236