为什么我们不能声明一个类型为void的变量? [英] Why can't we declare a variable of type void?

查看:770
本文介绍了为什么我们不能声明一个类型为void的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找该标准中对该事实的正式解释。
我发现了3.9.1 / 9的说法,并试图给出使用该部分的解释。



第3.9.1 / N3797


void type有一组空值。
不完整的类型。它用作不返回值的函数的返回
类型。任何表达式都可以
显式转换为类型cv void(5.4)。 void
类型的表达式只能用作表达式语句(6.2),作为
a逗号表达式(5.18)的操作数,作为?的第二个或第三个操作数:(5.16),
作为typeid,noexcept或decltype的操作数,作为
a中的表达式返回类型为void,
的函数的返回语句(6.6.3)或作为显式转换的操作数类型cv void。


我不明白它是如何意味着void类型有一组空值? / p>

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

  extern T v; 

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

  #include< iostream> 
#include< cstring>

using namespace std;

struct Foo;

extern Foo f; //好!

int main()
{
}




> #include< iostream>
#include< cstring>

using namespace std;

extern void f; //编译时错误

int main()
{
}

DEMO


<因为变量必须具有对象类型或引用,所以不能声明类型 void 的变量。 extern void f; 不声明引用, void 不是对象类型



第3节 [basic] 说:


通过非静态数据成员或对象的引用声明引入变量


第3.9节 [basic.types]


是一个(可能是cv限定的)类型,不是函数类型而不是引用类型, void 类型。



I'm looking for a formal explanation of that fact in the Standard. I've found what 3.9.1/9 says and trying to give an explanation used that section.

Section 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.

I don't understand how it implies from the fact that the void type has an empty set of values?

Suppose that type T has an empty set of values. Why does compiler throw an error when it come across the following line:

extern T v; 

We can decalre a variable of incomplete type in the following way:

#include <iostream>
#include <cstring>

using namespace std;

struct Foo;

extern Foo f; //OK!

int main()
{
}

and it works fine

DEMO

It cannot be done on a void type

#include <iostream>
#include <cstring>

using namespace std;

extern void f; //compile-time error

int main()
{
}

DEMO

解决方案

You cannot declare a variable of type void because variables must have object type or be references, extern void f; doesn't declare a reference, and void is not an object type:

Section 3 [basic] says that

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

Section 3.9 [basic.types] says that

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

这篇关于为什么我们不能声明一个类型为void的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆