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

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

只是一个简单的程序,但谁能指出为什么会出现此错误,(我使用的是 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:\Users\chetna\Documents\Untitled1.cpp [Error] 'cout' was not declared in this scope
1   0   C:\Users\chetna\Documents\Untitled1.cpp In file included from C:\Users\chetna\Documents\Untitled1.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();

注意main函数要这样声明

int main()

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

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

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

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

将您的主要功能声明为

int main()

不是void main(),因为标准 C++ 需要 main 函数 return 一个 int(0 表示成功)。

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