【发布时间】:2016-09-26 02:18:45
【问题描述】:
所以我正在尝试编写一个复制函数来复制动态分配的字符串数组的所有元素。
在我的头文件中,我将其定义为具有以下类型/返回值:
#include <algorithm>
#include <string>
using std::string
using std::copy
class StringSet{
public:
StringSet(const StringSet&);
为了实现,我有:
StringSet::StringSet(const StringSet& arr)
{
auto a2 = StringSet(size());
copy(arr,arr + size(), a2);
}
其中 size() 返回字符串数组的当前大小。 我对 operator= 也有这个限制
//prevent default copy assignment
StringSet& operator=(const StringSet&) = delete;
由于我没有将 operator+ 定义为类的一部分,并且限制 operator= 不能被包含在内,所以我遇到了一个问题。
这里明显的问题是我得到了错误:
error: no match for 'operator+' (operand types are 'const StringSet' and 'int')
如果不使用 + 或 = 运算符,我应该如何解决此错误?
StringSet 构造函数初始化一个动态分配的大小为“容量”的字符串数组
StringSet::StringSet(int capacity)
: arrSize{capacity},
arr{make_unique<string[]>(capacity)}
{
}
Copy 构造函数应该创建其参数的深层副本。
我的理解是,我需要为 std::copy 提供源 + 起始迭代器、源 + 结束迭代器和目标 + 起始迭代器作为其深拷贝的参数。
但是,我不想为此使用 std::copy 。在这种情况下,用于深度复制的 for 循环如何实现?
我尝试编写一个 for 循环,但我得到了 operator[] 的编译器错误
StringSet::StringSet(const StringSet& a)
{
auto a2 = StringSet(currentSize);
for (auto i=0; i < currentSize ; i++ )
{
a2[i] = a[i];
}
}
错误
error: no match for 'operator[]' (operand types are 'StringSet' and 'int')|
error: no match for 'operator[]' (operand types are 'const StringSet' and 'int')|
编辑:
我已经重载了 operator[]:
StringSet& operator[](const int);
这是新的错误
error: passing 'const StringSet' as 'this' argument discards qualifiers [-fpermissive]|
error: use of deleted function 'StringSet& StringSet::operator=(const StringSet&)'|
【问题讨论】:
-
你需要重载
+操作符。 -
不,您不需要重载
+运算符。无论您在StringSet类中为“动态分配的字符串数组”使用什么容器,都需要在复制构造函数中将其初始化为arr.size(),然后传递arr的容器的开始迭代器,结束迭代器, 和this的迭代器到 std::copy。 -
即使忽略您的代码在语法上不正确的事实,您也留下了太多信息,人们无法明智地帮助您。接受大小的构造函数是做什么的?
copy()对StringSet有什么作用?通过将大小添加到StringSet,您希望得到什么结果? -
@Peter 谢谢你,我现在就包含这些信息。
-
以不同于
copy(arr, arr + size(), a2);的方式实现您的复制构造函数
标签: c++ class c++14 copy-constructor deep-copy