【问题标题】:C++ copying a string array within context of defined classC ++在已定义类的上下文中复制字符串数组
【发布时间】: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


【解决方案1】:

你需要重载 + 运算符,大致:

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

顺便说一句,如果您的类可以同时支持输入和输出迭代器,那么您可以简单地使用std::copy(arr.first(), arr.last(), a2.first()),这当然会更好

【讨论】:

  • 我打算这样做 - 但想知道是否有其他方法可以做到这一点。似乎这可能是解决此问题的唯一方法。谢谢你的回答:)
  • @TigerCode 如果您认为这是正确的代码,请点击支持下方左侧的复选标记接受答案
  • 我正在寻找一个解决方案,我不必使用 std::copy 来复制数组内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2015-03-23
  • 2011-10-02
  • 2011-11-26
  • 1970-01-01
  • 2012-10-29
相关资源
最近更新 更多