gpt4 book ai didi

c++ - 是否有可能将 C++ 数组大小设置为函数的返回值

转载 作者:行者123 更新时间:2023-12-01 14:20:18 26 4
gpt4 key购买 nike

我对 C++ 还很陌生,所以请耐心等待:
我希望将数组的大小设置为函数的输出,例如:

//this is not the actual function, (go figure)
int getSizeInt(int size)
{
return size;
}

int main()
{
char charArray[getSizeInt(6)]; // Error: *function call must have a constant value in a constant expression*
return 0;
}

这可能是不可能的,老实说,我不知道。我在谷歌上搜索了这个问题,并一直在修补初始化数组的不同方法,但无济于事。

最佳答案

Is there a possible way to set a c++ array size to the return value of a function



是的。

数组变量的大小必须是编译时常量。如果函数是 constexpr,则函数调用是一个常量表达式它的参数本身就是常量表达式。

您的函数不满足这些约束,因此其返回值不能用作数组变量的大小。

然而,它可以用作动态数组的大小。创建动态数组的最简单方法是使用 std::vector (如果您打算表示文本,可以考虑使用 std::string 代替):
std::vector<char> charArray(getSizeInt(6));

关于c++ - 是否有可能将 C++ 数组大小设置为函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61671287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com