gpt4 book ai didi

c++ - 定义 const 数组类型的语法

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:53 27 4
gpt4 key购买 nike

请注意,我只对 C++ 语法的可能性感兴趣,而不是任何实际用途。

定义数组类型很容易。例如,int a[3];定义了一个数组类型为3的int,而const int a[3];int const a[3];定义了一个数组类型为3的const int。这三种形式都没有实际定义某种T 类型的const 数组(当然,它本身可以被const 修饰)。因此,以下代码将无法编译:

void f(int (&a)[3]) {...}

f({1, 2, 3});

原因很简单:一个非 const lval 引用不能绑定(bind)到一个 rval temporary。一种更正代码的方法是:

typedef int ArrOfInt[3];

void f(const ArrOfInt& a) {...}

f({1, 2, 3});

我的问题是:C++ 是否具有用于 const 数组类型的内联定义的语法,因此一开始就不需要 typedef

最佳答案

数组没有与其元素分开的 cv 限定,因此您要求的是不存在的东西。引用标准,

Any cv-qualifiers applied to an array type affect the array element type, not the array type (8.3.4).

(N3936 中的[basic.type.qualifier]/2)

但是,它接着说,当元素类型被限定时,数组类型也被认为是合格的:

... An array type whose elements are cv-qualified is also considered to have the same cv-qualifications as its elements.

([basic.type.qualifier]/5)

而且您编写的代码确实可以在没有 typedef 的情况下重写。声明符语法是

void f(const int (&a)[3]);

const 仍然附加到元素类型,但数组类型也是 const,因此引用是对 const 的左值引用> 类型。所以这就是它可以绑定(bind)到临时文件的原因。

关于c++ - 定义 const 数组类型的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29467795/

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