首页 > 解决方案 > 复制构造函数 C++ 没有正确复制指针

问题描述

我为我的类创建了一个复制构造函数。有谁知道为什么l1.ptrl2.ptr在编译后给我相同的地址?我做了很多次,不知道错误在哪里。

#include<iostream>
#include<string>

using namespace std;

class numb
{
public:
    int* ptr;
    numb(int = 3);
    numb(const numb&);
    virtual ~numb();
};

numb::numb(int x)
{
    this->ptr = new int(x);
}

numb::numb(const numb& l1)
{
    this->ptr = new int(*(l1.ptr));

}

numb::~numb()
{    
}

int main()
{
    numb l1(5), l2;
    l1 = l2;
    cout << l1.ptr << endl;
    cout << l2.ptr << endl;
    system("Pause");
    return 0;
}

标签: c++classconstructorcopy

解决方案


在这个片段中:

numb l1(5), l2;
l2 = l1;

第二行没有调用复制构造函数。相反,它正在调用复制赋值运算符。由于您尚未定义,因此您会得到一个浅拷贝。

您可以使用复制构造函数,如下所示:

numb l1(5);
numb l2(l1);

operator=为您的班级定义:

numb& operator=(const numb&);  // do a deep copy

推荐阅读