如何解决"cout was not declared in this scope"错误?

How can I resolve the "cout was not declared in this scope" error?

本文关键字:in declared this scope 错误 not cout 何解决 解决 was      更新时间:2023-10-16

这只是一个简单的程序,但任何人都能指出为什么会发生这个错误吗?(我使用的是dev C++5.11版本(

#include <stdio.h>
#include <conio.h>
class animal
{
public :
void sound();
void eat() ;
};
void animal::eat()
{
cout<<"i eat animal food" ; 

}

void animal::sound()
{
cout<<"i sound like an animal" ;
}
void main()
{
animal a ;
a.sound()
a.eat()
getch()
}

错误如下:

In member function 'void animal::eat()':
15  4   C:UserschetnaDocumentsUntitled1.cpp [Error] 'cout' was not declared in this scope
1   0   C:UserschetnaDocumentsUntitled1.cpp In file included from C:UserschetnaDocumentsUntitled1.cpp

至少你必须包括

#include <iostream>

using namespace std;

名称cout是在名称空间std中声明的。因此,要么使用上面显示的using指令,要么使用像这样的限定名称(更好(

std::cout<<"i eat animal food" ; 

另一种方法是使用using声明。例如

#include <iostream>
using std::cout;
//...
void animal::eat()
{
cout<<"i eat animal food" ; 
}

并删除此指令

#include <stdio.h>

还放置分号

a.sound();
a.eat();
getch();

注意功能主体应像一样声明

int main()

请停止使用旧的Borland C++等。

请改用符合现代标准的C++编译器(g++、clang、Microsoft Visual Studio(。

不要使用conio.h,它是一个非常旧的编译器专用库,而不是标准库。

不要使用stdio.h,它不是一个坏库,但它声明了几个C函数,而不是C++函数。

将您的主要功能声明为

int main()

而不是void main(),因为标准C++需要主函数返回int(0表示成功(。

不要使用cout,而是使用std::cout,因为它是一个表示在std命名空间中定义的标准输出的对象。