C++ g++ 在类头文件中找不到“字符串”类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4893857/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:52:03  来源:igfitidea点击:

C++ g++ can't find 'string' type in class header file

c++stringg++compiler-errors

提问by jbrennan

I'm new to C++ but I can't figure out why this won't compile for me. I'm running on a Mac, coding with Xcode, but I'm building with my own makefile from bash.

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

Anyway, I'm getting two compiler errors that "string" type can't be found, even though I've included . Any help would be welcomed. Code:

无论如何,即使我已经包含了 . 欢迎任何帮助。代码:

//#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

I include this file in my main.cpp, and elsewhere in main I use the stringtype and it works just fine. Though in main I have included iostreaminstead of string(for other purposes). Yes, I've also tried including iostream in my AppController class but it didn't solve anything (I didn't really expect it to, either).

我将这个文件包含在我的 main.cpp 中,在 main 的其他地方我使用了这个string类型,它工作得很好。虽然我主要包括iostream而不是string(出于其他目的)。是的,我也试过在我的 AppController 类中包含 iostream 但它没有解决任何问题(我也没有真正期望它)。

So I'm not really sure what the problem is. Any ideas?

所以我不确定问题是什么。有任何想法吗?

回答by Washu

string is in the std namespace.

字符串在 std 命名空间中。

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

Alternatively you can use

或者你可以使用

using namespace std;

However, this is a very bad thing to do in headers as it will pollute the global namespace for anyone that includes said header. It's ok for source files though. There is an additional syntax you can use (that has some of the same problems as using namespace does):

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

using std::string;

This will also bring the string type name into the global namespace (or the current namespace), and as such should generally be avoided in headers.

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