【问题标题】:Copying an array stored in one class to another class将存储在一个类中的数组复制到另一个类
【发布时间】:2021-06-14 20:37:47
【问题描述】:

我有一种情况,我需要将存储在一个类中的指针数组复制到另一个类。 在对this 问题的第二个回答之后,我创建了这个可重现的示例,说明我在实际项目中尝试做的事情。

#include <iostream>
#include <iterator>

struct A{};

class Something
{
public:
    static constexpr int nItems = 5;
    A* pA[nItems];
};

class AnotherThing
{
public:
    A* pACopy[Something::nItems];

    void CopyPointers(const A* pA[Something::nItems])
    {
        std::copy(std::begin(pA), std::end(pA), std::begin(pACopy));
    }
};

int main()
{
    Something something;
    AnotherThing anotherThing;
    anotherThing.CopyPointers(something.pA);
}

错误在std::copy(std::begin(pA), std::end(pA), std::begin(pACopy)); 行,错误是 no instance of overload function "std::begin" matches the argument liststd::end 也一样。

【问题讨论】:

  • #include &lt;algorithm&gt;

标签: c++


【解决方案1】:

void CopyPointers(const A* pA[Something::nItems]) 等价于void CopyPointers(const A** pA)pA 不是数组而是指针。

解决方法是改用指针算法:

void CopyPointers(const A* pA[])
{
    std::copy(pA, pA + Something::nItems, std::begin(pACopy));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多