gpt4 book ai didi

c++ - 直接将数组写入参数会在 C++ 中出错

转载 作者:行者123 更新时间:2023-12-05 08:24:50 25 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

template <typename VAR, unsigned int N>
int size(VAR (&arr)[N])
{
return sizeof(arr) / sizeof(arr[0]);
}

int main()
{
cout << size("Test"); //This is working

int x[] = {7, 5, 43, 8};
cout << endl
<< size(x); //And this works too

cout << endl
<< size({7, 9, 7, 9}); //When i try this its give me "no matching function for call to 'size'" error

return 0;
}

参数采用在参数外修改的字符串和数组。但我需要像上面的代码一样直接在函数内部编写数组。 大小({一些整数});

最佳答案

像这样声明函数参数

int size( const VAR (&arr)[N])

也就是说,您不能将临时对象与非常量左值引用绑定(bind)。

关于c++ - 直接将数组写入参数会在 C++ 中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70893268/

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