【发布时间】:2020-07-02 19:55:08
【问题描述】:
我为我的班级创建了一个复制构造函数。有谁知道为什么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& operator=(numb const&),阅读CppCoreGuidelines。 -
复制结构类似于
numb l2 = l1;。使用l2 = l1;,您可以复制 assignment。 -
记住rule of five。您缺少副本分配:
operator=() -
这只是出于好奇,还是你真的有这样的代码?那为什么是指针呢?您尝试通过使用指向单个
int的指针来解决的实际问题是什么?即使你有数组,为什么要使用指针和手动内存管理而不是std::vector?请了解the rules of three, five and zero。我强烈推荐零规则。 -
你的意思是
l2 = l1,不是l1 = l2,对吧?
标签: c++ class constructor copy