在下面的static_strlen实现中,为什么&和 str 周围的括号有必要吗?
如果我将类型更改为 const char str[Len]
,则会收到以下错误:
error: no matching function for call to ‘static_strlen(const char [5])’
我是否正确地认为 static_strlen
需要一个 const char 引用数组?我的理解是数组无论如何都是作为指针传递的,那么有什么必要将元素作为引用呢?或者这种解释完全不合时宜?
#include <iostream>
template <size_t Len>
size_t
static_strlen(const char (&str)[Len])
{
return Len - 1;
}
int main() {
std::cout << static_strlen("oyez") << std::endl;
return 0;
}
If I change the type to const char str[Len]
, I get the following error:
error: no matching function for call to ‘static_strlen(const char [5])’
Am I correct that static_strlen
expects an array of const char references? My understanding is that arrays are passed as pointers anyway, so what need is there for the elements to be references? Or is that interpretation completely off-the-mark?
#include <iostream>
template <size_t Len>
size_t
static_strlen(const char (&str)[Len])
{
return Len - 1;
}
int main() {
std::cout << static_strlen("oyez") << std::endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,函数参数是对
Len
const 字符数组的引用。这就是函数知道长度的方式(假设最后一个字节是 NUL 终止符,因此是 -1)。括号的作用正是为了阻止它成为你所认为的那样。实际上,C++ 中没有引用数组这样的东西,所以即使没有括号,它也不可能是您想象的那样。我猜(但不确定)需要括号只是为了与其他类似类型定义保持一致,例如指向数组的指针:
该示例还说明了为什么数组不是指针。预测以下程序的输出,然后运行它:
No, the function parameter is a reference to an array of
Len
const chars. That's how the function knows the length (assuming the last byte is a NUL terminator, hence the -1). The parentheses are there precisely to stop it being what you think it is.Actually there's no such thing in C++ as an array of references, so it couldn't be what you think it is even without the parens. I guess (but am not sure) that the need for the parens is just for consistency with other similar type definitions, such as pointers to arrays:
That example also illustrates why an array is not a pointer. Predict the output of the following program, and then run it:
这是创建函数以将数组的大小自动传递给函数的方法之一。
是一个函数,它接受恰好包含
Len
元素的const char
数组。数组大小必须在编译时已知。即该数组不是通过 new 或 malloc 分配的。更具体地说,该参数是对 Len 元素数组的引用,而不是实际的数组,这就是为什么它在传递时不会转换为指针。
This is one of the way that a function can be made such that the size of the array is passed into the function automatically.
is a function that takes in an array of
const char
of exactlyLen
elements. The array size must be known at compile time. I.e. the array wasn't allocated via new or malloc.To be more specific, the parameter is a reference to an array of
Len
elements, rather than an actual array, which is why it doesn't get converted into a pointer when passed.