【问题标题】:Why can't I declare a string in my program: "string is undeclared identifier"为什么我不能在我的程序中声明一个字符串:“字符串是未声明的标识符”
【发布时间】:2011-10-02 07:26:33
【问题描述】:

我不能在我的程序中声明一个字符串:

string MessageBoxText = CharNameTextBox->Text;

它只是不起作用。它说string is undeclared identifier。我在命名空间或包含或类似的东西中缺少什么?

【问题讨论】:

  • 谁说CharNameTextBox->Text 可以转换为std::string?

标签: c++ string visual-c++


【解决方案1】:

确保您已包含此标头:

#include <string>

然后使用std::string 而不是string。这是因为string 是在std 命名空间中定义的。

并且不要在命名空间范围内写这个:

using namespace std; //bad practice if you write this at namespace scope

但是,在函数范围内编写它并没有那么糟糕。但最好的是我之前建议的:

使用std::string

std::string MessageBoxText = CharNameTextBox->Text;

【讨论】:

  • 我在我的程序中应该把它放在哪里,我已经尝试过,但是无论我放在哪里,我都会收到一百行错误
  • 它必须位于文件顶部的任何其他代码之外。也许发布一些代码?
  • 你确定你编译的是 C++ 而不是 C?
  • 请不要向初学者推荐using namespace std;
  • 如果它只是 c 的话,我认为它不会被称为 Visual c++ :/
【解决方案2】:

要在 C++ 中使用标准的 string 类,您需要 #include &lt;string&gt;。添加 #include 指令后,string 将在 std 命名空间中定义,您可以将其称为 std::string

例如

#include <string>
#include <iostream>

int main()
{
    std::string hw( "Hello, world!\n" );
    std::cout << hw;
    return 0;
}

【讨论】:

  • 我刚刚编辑了斯科特的答案以使其更好,然后刷新页面,它也显示了你的。 +1。
【解决方案3】:

您是否以任何方式使用 C++/CLI(.NET 的 Microsoft 扩展)而不是标准 ISO C++ 进行编译?

在这种情况下,您应该执行以下操作:

System::String^ MessageBoxText = CharNameTextBox->Text;

另见以下文章:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    相关资源
    最近更新 更多