gpt4 book ai didi

c++ - 相同的 const 类型限定符

转载 作者:IT老高 更新时间:2023-10-28 13:00:37 26 4
gpt4 key购买 nike

一个类型有两个 const 会发出警告/错误。但是,如果类型已使用 typedef 定义,编译器会接受它(Visual Studio 2013 和在线编译器 C++ shell)。

#include <iostream>

typedef const int value_type;

int main()
{
const value_type n = 0; //ok
const const int n2 = 0; //error C4114

return 0;
}

有人知道为什么吗?是不是那个是const (const int),和const const int不一样?

最佳答案

在 typedef 情况下明确允许,而在声明本身中不允许:

[dcl.type/1]

The type-specifiers are:

type-specifier : ... cv-qualifier
defining-type-specifier : type-specifier

[dcl.spec/1 and 2]

The specifiers that can be used in a declaration are:

decl-specifier : ... defining-type-specifier ...

Each decl-specifier shall appear at most once in a complete decl-specifier-seq, except that long may appear twice.

[dcl.type.cv/1]

There are two cv-qualifiers, const and volatile. Each cv-qualifier shall appear at most once in a cv-qualifier-seq. If a cv-qualifier appears in a decl-specifier-seq, the init-declarator-list or member-declarator-list of the declaration shall not be empty. [ Note: [basic.type.qualifier] and [dcl.fct] describe how cv-qualifiers affect object and function types.  — end note ] Redundant cv-qualifications are ignored. [ Note: For example, these could be introduced by typedefs. — end note ]

除了类型别名之外,模板参数是限定符可能是多余的另一种情况。允许这样做的理由是不要仅仅因为 cv 限定符偷偷进入后门就破坏其他正确的声明。

关于c++ - 相同的 const 类型限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45478054/

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