在 class 成员函数中存储一个字符串数组并返回它

Storing a string array in a class member function and returning it

你好,如果有人花时间编写一种简单的方法来将字符串数组存储在 class 成员函数中,并 return 在主函数中存储该值,我将不胜感激。

这是我的。我想在这个数组中存储 4 个不同的作者,稍后打印。

  void setauthor(string a[4])
    {
        string authors[4] = a[4];
    }

谢谢

你不能像那样在构造时复制数组,但你可以在之后复制:

void setauthor(string a[4])
{
    string authors[4];
    std::copy(a, a+4, authors);
}

您需要 #include <algorithm> 在顶部。

只需使用具有复制语义的std::array<std::string, 4>

void setauthor(std::array<std::string, 4> a)
{
    std::array<std::string, 4> authors = a;
}

您需要 #include <array> 在顶部。

您甚至可以声明一个别名以方便编写:

using four_strings = std::array<std::string, 4>;

void setauthor(four_strings a)
{
    four_strings authors = a;
}

你为什么不使用简单的 for 循环?? 虽然你需要一个额外的参数,但如果作者编号是固定的那么这应该是最简单的。

void setauthor(string a[4],int number)
{
    string author[4];
    for(int i=0;i<number;i++)
    {
        author[i]= a[i];
        cout<<author[i];
    }
}