通过引用传递结构数组

Pass array of structs by reference

本文关键字:结构 数组 引用      更新时间:2023-10-16

我想将一个结构数组传递给一个函数。

struct Month {
std::string name;
int days;
};
Month months[12]{{"January", 31}, {"February", 28}, {"March", 31}, {"April", 30}, {"May", 31}, {"June", 30},
{"July", 31}, {"August", 31}, {"September", 30}, {"October", 31}, {"November", 30}, {"December", 31}};

我尝试将 month 数组传递给带有参数的函数:月份(&月份([]

编译器指出:"参数 1 没有已知的从 'main((::Month [12]' 到 'Month (&([12]' 的转换"。

然后,我尝试通过指针传递数组,为此,我首先在自由存储中分配了 month 数组的元素,如下所示。

Month* months[12]{new Month{"January", 31}, new Month{"February", 28}, new Month{"March", 31}, new Month{"April", 30}, new Month{"May", 31}, new Month{"June", 30},
new Month{"July", 31}, new Month{"August", 31}, new Month{"September", 30}, new Month{"October", 31}, new Month{"November", 30}, new Month{"December", 31}};

我尝试将此数组传递给带有参数的函数:月份**

编译器声明:"参数 1 没有从 'main((::Month* [12]' 到 'Month**' 的已知转换">

我想知道如何通过指针传递我的月份数组,以及是否也可以通过引用传递它。

是的,我知道使用向量会容易得多,但我几天前才开始学习C++,我想熟悉数组。

函数本身是空的,我无法在不知道我的参数是什么的情况下编写函数。

void print_table(Month** months) {
}

函数调用是:

print_table(months)

删除所有无关代码后,我只剩下这个:

struct Month;
void print_table(Month** months);
int main() {
struct Month {
std::string name;
int days;
}
Month* months[12]{new Month{"January", 31}, new Month{"February", 28}, new Month{"March", 31}, new Month{"April", 30}, new Month{"May", 31}, new Month{"June", 30},
new Month{"July", 31}, new Month{"August", 31}, new Month{"September", 30}, new Month{"October", 31}, new Month{"November", 30}, new Month{"December", 31}};
print_table(months);
}

约翰在评论中解释了这个问题,我也发布了更正后的代码。

由于您将Month的内容视为常量,因此只需传递一个右值引用,例如Month*&& m.例:

void showmonths (Month*&& m, size_t nmonths)
{
for (size_t i = 0; i < nmonths; i++)
std::cout << std::left << std::setw(12) << m[i].name << m[i].days << 'n';
}

有关引用声明和使用的其他详细信息,请参阅:引用声明

阅读 John 的评论后,我意识到问题是我的结构是在 main 函数内部声明的,如下所示:

struct Month;
void print_table(Month** months);
int main() {
struct Month {
std::string name;
int days;
}
Month* months[12]{new Month{"January", 31}, new Month{"February", 28}, new Month{"March", 31}, new Month{"April", 30}, new Month{"May", 31}, new Month{"June", 30},
new Month{"July", 31}, new Month{"August", 31}, new Month{"September", 30}, new Month{"October", 31}, new Month{"November", 30}, new Month{"December", 31}};
print_table(months);
}

我编辑以在主函数之外声明结构,它起作用了。谢谢!

struct Month {
std::string name;
int days;
}
void print_table(Month** months);
int main() {
Month* months[12]{new Month{"January", 31}, new Month{"February", 28}, new Month{"March", 31}, new Month{"April", 30}, new Month{"May", 31}, new Month{"June", 30},
new Month{"July", 31}, new Month{"August", 31}, new Month{"September", 30}, new Month{"October", 31}, new Month{"November", 30}, new Month{"December", 31}};
print_table(months);
}

试试这个

Month months[10];
//like this you can pass
print_table(months);

传递给此函数

void print_table(struct Month * months)
{
//code here
}