在 C++ 中返回结构数组

Returning struct array in c++

我正在尝试 return 我的 class 中的结构数组,但我一直收到错误

error C2556: 'cellValue *LCS::LcsLength(std::string,std::string)' : overloaded function differs only by return type from 'cellValue LCS::LcsLength(std::string,std::string)'

当我 return 在我的 .cpp 文件中时

我的 class 声明是:

enum arrow {UP, LEFT, DIAGONAL};

struct cellValue
{
    int stringLenght;
    arrow direction;
};

class LCS
{
public:
    cellValue LcsLength (string, string);
};

当我在我的函数中尝试 returning 时,我有:

cellValue LCS::LcsLength (string X, string Y)
{
    cellValue table[1024][1024];

    return table;
}

您的 LcsLength 函数有两个主要问题:您的 return 类型错误,并且您有一个悬空指针。

您将 LcsLength 声明为 return 一个 cellValue 对象,然后尝试 return 一个 cellValue[1024][1024]。这就是您遇到编译器错误的原因。

无论return类型如何,您所做的都不会起作用,因为table会在函数退出后立即销毁。使用 std::vectorstd::map 会更好,具体取决于 table 的用途。

cellValue LCS::LcsLength (string X, string Y)
{
    cellValue table[1024][1024];

    return table;
}

这里的问题在于理解局部数组 table 会衰减为 cellValue(*)[1024] 而不是 cellValue,这就是函数的 return 类型,按照定义。

另一个问题是,即使你修复了类型问题,你也会 returning 一个局部变量的指针,当函数超出范围时它会被销毁并且被调用者最终会得到悬空指针,即指向不再受您控制的位置的指针。

如果必须 return 一个对象集合,其所需大小在编译时已知,则应使用 std::array,否则请使用 Tartan 的建议,使用 std::vector。使用 C++11 的保证,您也不会对性能造成任何影响。