C++ 为什么我不能在我的程序中声明一个字符串:“字符串是未声明的标识符”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7625105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't I declare a string in my program: "string is undeclared identifier"
提问by Trent
I can't declare a string in my program:
我不能在我的程序中声明一个字符串:
string MessageBoxText = CharNameTextBox->Text;
it just doesn't work. It says string is undeclared identifier. What am I missing in the namespace or include or something like that?
它只是不起作用。它说string is undeclared identifier。我在命名空间或包含或类似的东西中缺少什么?
回答by
Make sure you've included this header:
确保您已包含此标题:
#include <string>
And then use std::stringinstead of string. It is because stringis defined in stdnamespace.
然后使用std::string代替string。这是因为string在std命名空间中定义。
And don't write this at namespace scope:
并且不要在命名空间范围内写这个:
using namespace std; //bad practice if you write this at namespace scope
However, writing it at function scope is not that bad. But the best is one which I suggested before:
但是,在函数范围内编写它并没有那么糟糕。但最好的是我之前建议的:
Use std::stringas:
使用std::string如:
std::string MessageBoxText = CharNameTextBox->Text;
回答by CB Bailey
To use the standard stringclass in C++ you need to #include <string>. Once you've added the #includedirective stringwill be defined in the stdnamespace and you can refer to it as std::string.
要string在 C++ 中使用标准类,您需要#include <string>. 添加#include指令后,string将在std命名空间中定义该指令,您可以将其称为std::string.
E.g.
例如
#include <string>
#include <iostream>
int main()
{
std::string hw( "Hello, world!\n" );
std::cout << hw;
return 0;
}
回答by dalle
Are you by any way compiling using C++/CLI, the Microsoft extension for .NET, and not standard ISO C++?
您是否以任何方式使用 C++/CLI、Microsoft .NET 扩展而不是标准 ISO C++ 进行编译?
In that case you should do the following:
在这种情况下,您应该执行以下操作:
System::String^ MessageBoxText = CharNameTextBox->Text;
Also see the following articles:
另请参阅以下文章:

