我在整体编程方面是新手。
我已经尝试阅读该语言的官方标准,但找不到我的问题的任何答案。
所以我需要了解 void 类型和 C++ 中其他不完整类型的主要区别是什么。例如:语言(或代码)中是否有可以使用 void 而不是其他不完整类型的地方,反之亦然?还是 void 在各个方面都像其他不完整类型一样?
最佳答案
void 和另一个不完整类型之间确实有一个非常细微的区别:
您不能引用 void 类型:
struct T; // incompletely defined type
// incompletely defined types and void are incomplete types
T* x=nullptr; // pointer to incomplete type are valid, same for void pointers
T& tref=*x; // it's valid to have a reference to an incompletely defined type
void& vref; // it's INVALID to have a reference to void, because no object could ever be void
int f(void &vt); // INVALID function declaration with invalid parameter: void reference
int g(T& vt); // valid function declaration using a parameter: reference to incomplete type
C++ 标准引号:
3.9/5: A class that has been declared but not defined, or an array of unknown size or of incomplete element type, is an incompletely-defined object type. Incompletely-defined object types and the void types are incomplete types
3.9/8: An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.
8.3.2/1: A declarator that specifies the type “reference to cv void” is ill-formed.
可以将任何表达式转换为void,这显然不是其他不完整类型的情况:
(void)(3 + 5); // OK explicit conversion to void
(T)(3 + 5); // Invalid expression to an incomplete type
这在 C++ 标准中有记录:
3.9.1/9: Any expression can be explicitly converted to type cv void
关于c++ - void 和 C++ 中其他不完整类型的主要区别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27080061/