C++: char(nextchar);它有什么作用

C++: char(nextChar); what doess it do

本文关键字:什么 作用 char nextchar C++      更新时间:2023-10-16

这有什么作用: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);
}

它使用重载std::string::operator += (char)char(nextChar)追加到std::string foundChar,然后丢弃字符串。

char(nextChar)是从intchar的强制转换(因为nextChar被声明为int)——相当于(char)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);

不。

此操作的行为未定义,因为

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圈外。

char(nextChar) 是从 int 数据类型转换为 char 数据类型的类型转换 - 相当于 (char)nextChar

有关更多详细信息,请转到下面的链接