【问题标题】:C++ g++ can't find 'string' type in class header fileC++ g++ 在类头文件中找不到“字符串”类型
【发布时间】:2011-06-21 02:24:39
【问题描述】:

我是 C++ 新手,但我不知道为什么它不能为我编译。我在 Mac 上运行,使用 Xcode 进行编码,但我正在使用自己的 bash 生成文件进行构建。

无论如何,我得到了两个编译器错误,即找不到“字符串”类型,即使我已经包含了 .欢迎任何帮助。代码:

//#include <string> // I've tried it here, too. I'm foggy on include semantics, but I think it should be safe inside the current preprocessor "branch"
#ifndef APPCONTROLLER_H
#define APPCONTROLLER_H

#include <string>
class AppController {
// etc.
public:
    int processInputEvents(string input); //error: ‘string’ has not been declared
    string prompt(); //error: ‘string’ does not name a type
};
#endif

我将此文件包含在我的 main.cpp 中,在 main 的其他地方我使用 string 类型,它工作得很好。虽然我主要包括iostream而不是string(用于其他目的)。是的,我也尝试在我的 AppController 类中包含 iostream,但它没有解决任何问题(我也没想到会这样)。

所以我不太确定问题出在哪里。有什么想法吗?

【问题讨论】:

    标签: c++ string g++ compiler-errors


    【解决方案1】:

    字符串在 std 命名空间中。

    #include <string>
    ...
    std::string myString;
    

    你也可以使用

    using namespace std;
    

    但是,在标头中这样做是一件非常糟糕的事情,因为它会污染包含该标头的任何人的全局命名空间。不过源文件没问题。您可以使用另一种语法(与 using namespace 存在一些相同的问题):

    using std::string;
    

    这也会将字符串类型名称带入全局命名空间(或当前命名空间),因此通常应避免在标题中使用。

    【讨论】:

    • +1 以获得很好的描述答案。提及可能的实施方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多