首页 > 编程笔记 > C++笔记 阅读:6

C++拷贝构造函数(复制构造函数)的用法(附带实例)

C++实际开发中,有时需要为对象保存一个副本,以便在需要时恢复对象的状态,这时就要用到复制构造函数。

所谓复制构造函数,其本质上仍然是一个构造函数,但函数参数是一个已初始化的类对象。通过复制构造函数,可快速为对象建立一个一模一样的副本。

【实例】复制构造函数。
1) 在头文件 Person.h 中声明和定义类,程序代码如下:
class CPerson //定义CPerson类
{
public:
    CPerson(int iIndex, short shAge, double dSalary); //声明构造函数(带参数)
    CPerson(CPerson &copyPerson); //声明复制构造函数,参数是一个已初始化的类对象

    int m_iIndex;
    short m_shAge;
    double m_dSalary;

    int getIndex();
    short getAge();
    double getSalary();
};

CPerson::CPerson(int iIndex, short shAge, double dSalary) //定义构造函数(带参数)
{
    m_iIndex = iIndex;
    m_shAge = shAge;
    m_dSalary = dSalary;
}

CPerson::CPerson(CPerson& copyPerson) //定义复制构造函数,参数是一个已初始化的类对象
{
    m_iIndex = copyPerson.m_iIndex;
    m_shAge = copyPerson.m_shAge;
    m_dSalary = copyPerson.m_dSalary;
}

short CPerson::getAge() //成员函数getAge()
{
    return m_shAge;
}

int CPerson::getIndex() //成员函数getIndex()
{
    return m_iIndex;
}

double CPerson::getSalary() //成员函数getSalary()
{
    return m_dSalary;
}

2) 在主程序文件中实现类对象的调用,程序代码如下:
#include <iostream>
#include "Person.h"
using namespace std;

int main()
{
    CPerson p1(20, 30, 100);    // 通过构造函数声明对象 p1
    CPerson p2(p1);    // 通过复制构造函数声明对象 p2

    cout << "m_iIndex of p1 is:" << p1.getIndex() << endl;    // 输出对象p1的3个成员函数
    cout << "m_shAge of p1 is:" << p1.getAge() << endl;
    cout << "m_dSalary of p1 is:" << p1.getSalary() << endl;

    cout << "m_iIndex of p2 is:" << p2.getIndex() << endl;    // 输出对象p2的3个成员函数
    cout << "m_shAge of p2 is:" << p2.getAge() << endl;
    cout << "m_dSalary of p2 is:" << p2.getSalary() << endl;
}
程序运行结果为:

m_iIndex of p1 is:20
m_shAge of p1 is:30
m_dSalary of p1 is:100
m_iIndex of p2 is:20
m_shAge of p2 is:30
m_dSalary of p2 is:100

程序中先用带参数的构造函数声明对象 p1,然后通过复制构造函数声明对象 p2,因为 p1 已经是初始化完成的类对象,可以作为复制构造函数的参数。通过输出结果可以看出,两个对象是完全相同的。

相关文章