~May~ 发表于 5 天前

面向对象-拷贝构造函数

#include <iostream>

using namespace std;

// 构造函数:
//                C++中的构造函数可以分为哪些类型?
//                -按照参数:有参构造、无参构造
//                -按照类型:普通构造、拷贝构造

// 拷贝构造:
//                根据一个对象,拷贝出另一个对象。新的对象与原来的对象地址不同,属性值相同
//                这个属性的拷贝操作,是在拷贝构造函数中完成的。
//                系统会自动提供拷贝构造函数

class Person {
public:
        string name;
        int age;

        Person() {}
        Person(string name, int age) :name(name), age(age) {}

        Person(const Person& p) {
                cout << "拷贝构造函数调用了" << endl;
                name = p.name;
                age = p.age;
        }
};

int main() {
        // 创建对象
        Person xiaoming("xiaoming", 19);
        //类似于int x=10;int y=x;
        //创建了一个新的对象xiaohei,xiaohei和xiaoming指向的空间是不同的,只是拥有同样的属性值
        //这个过程会自动调用拷贝构造函数
        Person xiaohei = xiaoming;
       
        cout << xiaoming.age << endl;
        cout << xiaohei.age << endl;
        return 0;
}

FishC 发表于 5 天前

你的代码片段最后是未完成的。你可以继续如下编写,补全拷贝构造函数:

#include <iostream>
#include <string>

using namespace std;

// 构造函数:
// C++中的构造函数可以分为哪些类型?
// -按照参数:有参构造、无参构造
// -按照类型:普通构造、拷贝构造

class Person {
public:
    string name;
    int age;

    Person() {}
    Person(string name, int age) :name(name), age(age) {}

    // 拷贝构造函数
    Person(const Person& p) {
      cout << "拷贝构造函数调用" << endl;
      name = p.name;
      age = p.age;
    }
};

int main() {
    Person p1("张三", 30);
    Person p2 = p1; // 调用拷贝构造函数

    cout << "p1: " << p1.name << ", " << p1.age << endl;
    cout << "p2: " << p2.name << ", " << p2.age << endl;

    return 0;
}

在上述代码中,我们定义了一个 Person 类,并提供了一个拷贝构造函数。该函数会在利用一个现有对象创建新对象时被调用。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 面向对象-拷贝构造函数