C++ C++;在已定义类的上下文中复制字符串数组

C++ C++;在已定义类的上下文中复制字符串数组,c++,class,c++14,copy-constructor,deep-copy,C++,Class,C++14,Copy Constructor,Deep Copy,因此,我试图编写一个复制函数来复制动态分配的字符串数组的所有元素 在头文件中,我将其定义为具有以下类型/返回值: #include <algorithm> #include <string> using std::string using std::copy class StringSet{ public: StringSet(const StringSet&); 其中size()返回字符串数组的当前大小。 我对运算符也有此限制= //prev

因此,我试图编写一个复制函数来复制动态分配的字符串数组的所有元素

在头文件中,我将其定义为具有以下类型/返回值:

#include <algorithm> 
#include <string>
using std::string
using std::copy

class StringSet{
  public:
     StringSet(const StringSet&);
其中size()返回字符串数组的当前大小。 我对运算符也有此限制=

//prevent default copy assignment
StringSet& operator=(const StringSet&) = delete;
因为我没有将操作符+定义为类的一部分,并且对操作符=有一个不包含的限制,所以我遇到了一个问题

这里明显的问题是我得到了错误:

error: no match for 'operator+' (operand types are 'const StringSet' and 'int')
在不使用+或=运算符的情况下,如何处理此错误

StringSet构造函数初始化大小为“capacity”的动态分配字符串数组

StringSet::StringSet(int capacity)
: arrSize{capacity},
    arr{make_unique<string[]>(capacity)}
{
}
编辑:

我重载了运算符[],如下所示:

StringSet& operator[](const int);
这是新的错误

error: passing 'const StringSet' as 'this' argument discards qualifiers [-fpermissive]|
error: use of deleted function 'StringSet& StringSet::operator=(const StringSet&)'|

您需要重载+运算符,大致如下:

class StringSet{
  public:
     StringSet(const StringSet&);
     StringSet& operator+(const StringSet& , int);

顺便说一句,如果你的类可以同时支持输入和输出迭代器,那么你可以简单地使用
std::copy(arr.first(),arr.last(),a2.first())
,这当然更好,你需要重载
+
操作符。不,你不需要重载
+
操作符。在
StringSet
类中为“动态分配的字符串数组”使用的任何容器,都需要在复制构造函数中将其初始化为
arr.size()
,然后传递
arr
容器的开始迭代器、结束迭代器,而
这个
的迭代器是std::copy。即使忽略您的代码在语法上不正确的事实,您也留下了太多的信息供人们明智地帮助您。接受大小的构造函数做什么?
copy()
StringSet
有什么作用?通过向
StringSet
添加一个大小,您希望得到什么结果?@Peter谢谢,我现在将包含该信息。以与通过
copy(arr,arr+size(),a2)不同的方式实现您的复制构造函数我本来打算这么做的,但我想知道是否还有其他方法可以做到这一点。看来这可能是解决这个问题的唯一办法。感谢您的回答:)@TigerCode如果您认为这是正确的代码,请单击upvoteI下方左侧右侧的复选标记来接受答案。我正在寻找一种不必使用std::copy来复制数组内容的解决方案。
StringSet& operator[](const int);
error: passing 'const StringSet' as 'this' argument discards qualifiers [-fpermissive]|
error: use of deleted function 'StringSet& StringSet::operator=(const StringSet&)'|
class StringSet{
  public:
     StringSet(const StringSet&);
     StringSet& operator+(const StringSet& , int);