gpt4 book ai didi

c++ - 为什么我们不能声明一个 void 类型的变量?

转载 作者:IT老高 更新时间:2023-10-28 12:32:25 28 4
gpt4 key购买 nike

我正在标准中寻找对这一事实的正式解释。我找到了 3.9.1/9 所说的内容,并尝试使用该部分进行解释。

第 3.9.1/9 节,N3797:

The void type has an empty set of values. The void type is an incomplete type that cannot be completed. It is used as the return type for functions that do not return a value. Any expression can be explicitly converted to type cv void (5.4). An expression of type void shall be used only as an expression statement (6.2), as an operand of a comma expression (5.18), as a second or third operand of ?: (5.16), as the operand of typeid, noexcept, or decltype, as the expression in a return statement (6.6.3) for a function with the return type void, or as the operand of an explicit conversion to type cv void.

我不明白 void 类型具有一组空值这一事实意味着什么?

假设类型 T 有一组空值。为什么编译器遇到以下行时会抛出错误:

extern T v; 

我们可以通过以下方式对不完整类型的变量进行 decal:

#include <iostream>
#include <cstring>

using namespace std;

struct Foo;

extern Foo f; //OK!

int main()
{
}

效果很好

DEMO

它不能在 void 类型上完成

#include <iostream>
#include <cstring>

using namespace std;

extern void f; //compile-time error

int main()
{
}

DEMO

最佳答案

您不能声明 void 类型的变量,因为变量必须具有对象类型或者是引用,extern void f; 不声明引用,并且 void 不是对象类型:

第 3 节 [basic] 这么说

A variable is introduced by the declaration of a reference other than a non-static data member or of an object.

第 3.9 节 [basic.types] 这么说

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.

关于c++ - 为什么我们不能声明一个 void 类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25853258/

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