C++ 在类成员函数中存储字符串数组并返回它
您好,如果有人花时间编写一种简单的方法,在类成员函数中存储字符串数组并在主函数中返回该值,我将不胜感激 这是我的。我想在此数组中存储4个不同的作者,稍后再打印C++ 在类成员函数中存储字符串数组并返回它,c++,arrays,string,class,C++,Arrays,String,Class,您好,如果有人花时间编写一种简单的方法,在类成员函数中存储字符串数组并在主函数中返回该值,我将不胜感激 这是我的。我想在此数组中存储4个不同的作者,稍后再打印 void setauthor(string a[4]) { string authors[4] = a[4]; } 谢谢您不能在这样的构造中复制阵列,但您可以在以后进行复制: void setauthor(string a[4]) { string authors[4]; std::c
void setauthor(string a[4])
{
string authors[4] = a[4];
}
谢谢您不能在这样的构造中复制阵列,但您可以在以后进行复制:
void setauthor(string a[4])
{
string authors[4];
std::copy(a, a+4, authors);
}
您需要在顶部包含。只需使用具有复制语义的
std::array
:
void setauthor(std::array<std::string, 4> a)
{
std::array<std::string, 4> authors = a;
}
void setauthor(std::数组a)
{
std::array authors=a;
}
您需要将#包括在顶部
您甚至可以声明别名以便于编写:
using four_strings = std::array<std::string, 4>;
void setauthor(four_strings a)
{
four_strings authors = a;
}
使用四个字符串=std::array;
void setauthor(四个字符串a)
{
四位作者=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];
}
}
void setauthor(字符串a[4],整数)
{
字符串作者[4];
对于(ItI= 0;IdCase:STD::/CODE)使用STD::Vector。它更容易通过、复制和存储。很抱歉,我已经开始C++中的一个类,只学习基础知识,我还没有学习过向量。在《初学者教育》中,<>代码>:STD::向量< /> >和<代码>:STD::/SCOD> >比原始数组更基本。我可以将字符串存储到该代码中。像这样?Book[i]。setauthor(author)为什么需要传递number
?为什么在每一步都打印author[i]
?为什么不使用std::copy
?author[i]用于检查,而我没有使用std::copy,因为我想让它尽可能简单:)