题解 | #浅拷贝和深拷贝#

浅拷贝和深拷贝

https://www.nowcoder.com/practice/535753110cbd4e8987adc2e67f392ab7

#include <iostream>
#include <cstring>
#pragma warning(disable : 4996)
using namespace std;

class Person {

    public:
        char* name; // 姓名
        int age;    // 年龄

        Person(const char* name, int age) {
            this->name = new char[strlen(name) + 1];
            strcpy(this->name, name);
            this->age = age;
        }

        // write your code here......
        Person(const Person &other) {
            this->name = new char[strlen(other.name) + 1];
            strcpy(this->name, other.name);
            this->age = other.age;
        }

        void showPerson() {
            cout << name << " " << age << endl;
        }

        ~Person() {
            if (name != nullptr) {
                delete[] name;
                name = nullptr;
            }
        }

};

int main() {

    char name[100] = { 0 };
    int age;

    cin >> name;
    cin >> age;

    Person p1(name, age);
    Person p2 = p1;

    p2.showPerson();

    return 0;
}

全部评论

相关推荐

02-10 12:23
已编辑
新余学院 C++
采集想要offer:专业技能那里要一条一条的列出来吧,感觉你项目很厉害了,但是如果你不写技术栈面试官对你项目不太懂的话都没办法问你八股😂C++都是基架岗,都是一群9✌🏻在卷,我觉得你要是有时间学个go把MySQL和redis写上去找个开发岗吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务