[英]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();
注意 function main 应声明为
int main()
请停止使用旧的 Borland C++ 等。
请改用符合现代标准的 C++ 编译器(g++、clang、Microsoft Visual Studio)。
不要使用 conio.h,它是一个非常古老的编译器专用库,而不是标准库。
不要使用 stdio.h 它不是一个坏库,但它声明了几个 C 函数,而不是 C++ 函数。
将您的主要 function 声明为
int main()
不是void main()
,因为标准 C++ 需要主 function 返回一个 int (0 表示成功)。
不要使用cout
,而是使用std::cout
,因为它是一个 object ,代表在std
命名空间内定义的标准 output 。
这对我有帮助。 我在使用 MinGW for vscode for cp(竞争性编程)设置 C++ 时遇到了这个错误。
它无处可寻。 参考上面的截图,如果你有那个扩展的错误信息,那么你的 iostream 库文件可能有问题。 如果您使用 Vscode,请CTRL + Click
。
ostreamcout
第 61 行之间的空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.