c++ - 复制构造函数 C++ 没有正确复制指针
问题描述
我为我的类创建了一个复制构造函数。有谁知道为什么l1.ptr
并l2.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;
}
解决方案
在这个片段中:
numb l1(5), l2;
l2 = l1;
第二行没有调用复制构造函数。相反,它正在调用复制赋值运算符。由于您尚未定义,因此您会得到一个浅拷贝。
您可以使用复制构造函数,如下所示:
numb l1(5);
numb l2(l1);
或operator=
为您的班级定义:
numb& operator=(const numb&); // do a deep copy
推荐阅读
- html - 更改悬停状态图标的颜色
- python - 如何将 FunctionName(t1: datetime, t2: datetime): 转换为 Python 2
- linux - 如何从 yum 生成可用更新列表并导出到 CSV,包括每个包的当前和更新版本?
- ruby-on-rails - 有什么方法可以访问称为单例方法的 Parent 对象吗?
- c# - Entity Framework Core:循环或多个级联路径
- git - 使用 Gitlab 管道和 git push 防止无限循环
- java - 如何在类和使用它的片段之间进行通信?
- javascript - 菜单(不接受 JavaScript)
- c++ - 测量 OpenCL 应用程序的运行时间
- javascript - 如何选择一个带参数的孩子进入 React