这是做什么的:char(nextChar)。我没有名为 char 的变量。我是在这里调用 char 类构造函数还是什么?
int nextChar;
while ((nextChar == stream.get()) != EOF)
{
// Convert it to a string for lookup in the symbol table
string foundChar = "";
foundChar += char(nextChar);
}
这是做什么的:char(nextChar)。我没有名为 char 的变量。我是在这里调用 char 类构造函数还是什么?
int nextChar;
while ((nextChar == stream.get()) != EOF)
{
// Convert it to a string for lookup in the symbol table
string foundChar = "";
foundChar += char(nextChar);
}
它附加char(nextChar)到std::string foundCharusing 重载std::string::operator += (char),然后丢弃字符串。
char(nextChar)是从intto的转换char(因为nextChar被声明为int) - 等价于(char)nextChar.
this 的行为是未定义的,因为
while ((nextChar == stream.get()) != EOF)
不考虑stream.get()而是nextChar比较这两个值。在那之后 nextChar 仍然保存它在(丢失的)初始化之后所做的内存垃圾。
可能它的目的是分配值并将其与 EOF 进行比较:
while ((nextChar = stream.get()) != EOF)
此外char(nextChar),有效地做与更常用的相同(char)nextChar,甚至更好static_cast<char>(nextChar)
顺便提一句:
int nextChar;
while ((nextChar = stream.get()) != EOF) { }
可以安全地缩短为
while ((int nextChar = stream.get()) != EOF) { }
只要你不需要nextChar在循环之外。
语法T(exp)是一个强制转换,等价于(T)(exp)(但T()对应于默认构造函数,T(exp1, exp2, ...)也调用相应的构造函数)。这意味着
int* ptr;
int i = int(ptr);
是允许的(在与 相同的条件和相同的含义下reinterpret_cast<int>(ptr)),而
int j = static_cast<int>(ptr);
int k(ptr);
不是。
char(nextChar) 是从 int 数据类型到 char 数据类型的类型转换 - 相当于 (char)nextChar