我在主题、文章和 SO 答案中读到#define
值没有类型,我已经围绕这个概念下定决心,认为类型是容器变量的属性,而不是值本身的属性:
const char cVALUE = 100; // 'cVALUE' is char with value 100, wich type is '100'?
const short sVALUE = 100; // 'sVALUE' is short with value 100, wich type is '100'?
const int iVALUE = 100; // 'iVALUE' is int with value 100, wich type is '100'?
#define VALUE 100 // wich type is 'VALUE'?
但是,值后缀呢?
#define VALUE_L 100l // 'VALUE_L' is long?
#define VALUE_UL 100ul // 'VALUE_UL' is unsigned long?
#define VALUE_LL 100ll // 'VALUE_LL' is long long?
#define VALUE_ULL 100ull // 'VALUE_ULL' is unsigned long long?
在上面的代码中,类型似乎是附加到值的,所以所有这些原始值都是类型化的值,与我之前读到的相反。但还有更多!文本文字甚至有限定符,例如:
#define TEXT "Text" // '"Text"' is an array of some kind of chars.
上面的文本值#define
具有类型(字符类型,如果您正在使用 MSVC,我认为字符类型可能会改变项目设置 -> 字符集,不知道在其他 IDE 中是否可能)它也有const
cualifier 并且它是 LValue 而不是 RValue,数字和文本文字之间的所有这些行为差异都让我感到不安。
所以,假设字符类型是char
,文字的类型"Text"
是const char *
,const char * const
还是const char[5]
?或者至少,在根据上下文推断出正确的类型之前,它根本没有类型?
而且,在 C++11 标准中,文本文字也可以使用一些前缀来设置字符集:
#define TEXT L"Text" // wide string with char type wchar_t
#define TEXTu8 u8"Text" // UTF-8 string with char type char
#define TEXTu u"Text" // UTF-16 string with char type char16_t
#define TEXTU U"Text" // UTF-32 string with char type char32_t
After thinking about all this stuff, I'm pretty confused, so I'm begging for some advice:
- Why is common knowledge that the literal values (and
#define
s) have no type but a type can be specified with the literal? in other words: Assert that the value literals have no type is false? - A value literal without suffix and no decimals (like
100
), can always be considered of type int? - Which is the type and qualifiers of the text literals, even considering its prefixes?