C++ 不将字符串识别为关键字
C++ does not recognize string as keyword
我尝试了以下代码:
#include <iostream>
using namespace std;
int main()
{
char string[4]='xyz';
return 0;
}
由于字符串是关键字,因此编译器应该给出错误,但它运行良好。谁能解释一下为什么编译成功。
string
不是关键字。
标准库中声明的类型名称。
当您给它命名时,您就是在做一种叫做阴影的事情。这在以下示例中更清楚:
{
int x = 0;
{
int x = 5;
std::cout << x << std::endl;
}
std::cout << x << std::endl;
}
打印什么?
嗯,先5
然后0
。
这是因为第二个作用域中的 x 覆盖了第一个作用域中的 x。它“遮盖”了第一个声明。
这也适用于类型名称:
struct MyStruct {
int x;
};
...
{
...
int MyStruct = 10;
...
}
在这里,MyStruct 在该范围内被覆盖。
同样的事情发生在你的例子 std::string
我尝试了以下代码:
#include <iostream>
using namespace std;
int main()
{
char string[4]='xyz';
return 0;
}
由于字符串是关键字,因此编译器应该给出错误,但它运行良好。谁能解释一下为什么编译成功。
string
不是关键字。
标准库中声明的类型名称。
当您给它命名时,您就是在做一种叫做阴影的事情。这在以下示例中更清楚:
{
int x = 0;
{
int x = 5;
std::cout << x << std::endl;
}
std::cout << x << std::endl;
}
打印什么?
嗯,先5
然后0
。
这是因为第二个作用域中的 x 覆盖了第一个作用域中的 x。它“遮盖”了第一个声明。
这也适用于类型名称:
struct MyStruct {
int x;
};
...
{
...
int MyStruct = 10;
...
}
在这里,MyStruct 在该范围内被覆盖。
同样的事情发生在你的例子 std::string