返回
c++ 编译器抗议:“string” 并非名字啊! —— error C2059 "string" illegal token on right side of '::' 。**
见解分享
2023-12-13 06:34:29
最近,项目里出现了一个奇怪的编译错误,乍看错误提示,真有丈二的和尚,摸不着头脑的感觉。解决之后,又是这么的合情合理。具体是什么样的问题呢?一起来看看吧。
说明:实际项目中的错误隐藏的更深,完全没有相关的错误提示。因为不方便用项目代码演示,准备了一个简单的例子,大家可以新建一个控制台项目,代码如下:
#include <string>
int main() {
std::string str = "Hello, world!";
return 0;
}
将此代码复制到 Visual Studio 中,编译器就会报错,错误信息如下:
error C2059: syntax error: 'string' illegal token on right side of '::'
面对这个错误信息,很多人都会一脸懵。这错到底出在哪儿?
我们再来看看这段代码:
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
return 0;
}
只要把 std::
去掉,错误就消失了。
原来,问题出在 std::string
上。
在 C++ 中,std::string
是一个标准库中的类型,它表示一个字符串。但是,如果你想在代码中使用它,你必须先包含它的头文件,即 #include <string>
。
包含头文件后,你就可以在代码中使用 std::string
了。但是,如果你不使用 using namespace std;
,那么你必须在使用 std::string
时加上 std::
前缀。
例如,以下代码是合法的:
#include <string>
int main() {
std::string str = "Hello, world!";
return 0;
}
而以下代码是错误的:
#include <string>
int main() {
string str = "Hello, world!";
return 0;
}
因为你没有使用 using namespace std;
,所以你必须在使用 std::string
时加上 std::
前缀。
知道了这个问题的原因,我们就可以轻松地解决它了。只需要在代码中添加 using namespace std;
即可。
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
return 0;
}
现在,代码就可以正常编译和运行了。
希望这个例子能帮助你理解 C++ 中的命名空间和 using 指令。