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

浅拷贝和深拷贝

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& person)
        {
            this->name = new char[strlen(person.name) + 1];
            strcpy(this->name, person.name);
            this->age = person.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;
}

拷贝构造函数,记得char数组要用new开辟空间。

C++题解 文章被收录于专栏

记录在牛客网用C++刷题的题解思路

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-29 20:12
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:27
明天又是董事长面,啥时候是个头啊
在太阳里长大的人:公司就仨人吧😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务