Skip to content

对于 https://csguide.cn/cpp/object_oriented/deep_copy_and_shallow_copy.html 中的代码有些疑问 #85

@EdGrass

Description

@EdGrass

对于 https://csguide.cn/cpp/object_oriented/deep_copy_and_shallow_copy.html 中的代码有些疑问:作者给出的代码即使我删去深拷贝的部分,也就如下代码,仍然没有出现修改一方会影响另一方的现象

#include <iostream>
#include <cstring>

class MyClass {
public:
    MyClass(const char* str) {
        data = new char[strlen(str) + 1];
        strcpy(data, str);
    }

    // 深拷贝的拷贝构造函数
    // MyClass(const MyClass& other) {
    //     data = new char[strlen(other.data) + 1];
    //     strcpy(data, other.data);
    // }

    // 深拷贝的赋值运算符重载
    // MyClass& operator=(const MyClass& other) {
    //     if (this == &other) {
    //         return *this;
    //     }
        
    //     delete[] data;
    //     data = new char[strlen(other.data) + 1];
    //     strcpy(data, other.data);
        
    //     return *this;
    // }
    
   void SetString(const char* str) {
     if (data != NULL) {
       delete[] data;
     }
     data = new char[strlen(str) + 1];
     strcpy(data, str);
   }
   
    ~MyClass() {
        delete[] data;
    }

    void print() {
        std::cout << data << std::endl;
    }

private:
    char* data;
};

int main() {
    MyClass obj1("Hello, World!");
    MyClass obj2 = obj1; // 深拷贝

    obj1.print(); // 输出:Hello, World!
    obj2.print(); // 输出:Hello, World!

    // 修改obj2中的数据,不会影响obj1,反之亦然
    obj2.SetString("Test");
    obj1.print(); // 输出:Hello, World!
    obj2.print(); // 输出:Test
    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions