我是C ++的新手,但我无法弄清楚为什么这不会为我编译。我在Mac上运行,使用Xcode进行编码,但我正在用bash构建自己的makefile。
无论如何,我得到两个编译器错误,即使我已经包含了“字符串”类型也无法找到。任何帮助都会受到欢迎。代码:
//#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,但它没有解决任何问题(我也没想到它)。
所以我不确定问题是什么。有什么想法吗?
答案 0 :(得分:31)
string在std名称空间中。
#include <string>
...
std::string myString;
或者你可以使用
using namespace std;
但是,这在标题中是一件非常糟糕的事情,因为它会污染包含所述标题的任何人的全局命名空间。但是对于源文件来说还可以。您可以使用其他语法(与使用命名空间有一些相同的问题):
using std::string;
这也会将字符串类型名称带入全局名称空间(或当前名称空间),因此通常应在标题中避免使用。