Cout不命名类型

cout does not name a type

本文关键字:类型 Cout      更新时间:2023-10-16

我是c++的新手,我在"hello world"程序上,我一直得到错误

"cout"没有命名类型,我在Ubuntu上使用的是geany,如果有区别的话,下面是我的代码:

#include <iostream>
int main ()
{
extern cout << "hello world!";
    return 0;
}

我不想做一个新的问题,所以我要把它添加到这里

有了提供的修订,它现在可以编译了,但是当我运行程序时,我得到了错误

./geany_run_script.sh: 5: ./geany_run_script.sh: ./hello: not found

对此有什么想法吗?

extern改为std::。第一个问题是extern仅在类型名称之前有效,所以这就是编译器抱怨的问题。第二个原因是cout在名称空间std中定义,因此需要告诉编译器在那里查找。好在代码没有写using namespace std;

变化:

extern cout << "hello world!";

std::cout << "hello world!";  // You probably want n on the end.

这是因为cout是在命名空间std中定义的对象。因此,您需要通过给它加上std::前缀来让编译器知道在哪里可以找到它。有几种可选择的技术,但在我看来这是最好的。

备选方案:使用using directive

using std::cout;
cout << "hello world!";

using std::cout;告诉编译器std中有一个叫做cout的对象,我们想在本地使用它,它被带到当前上下文中,从而允许你直接使用它。