我开始在www.learncpp.com和here学习c++,我读到,使用名称“cout”或“cin”定义我们自己的对象没有问题,因为C++将标准库中的所有功能都移到了std 命名空间。但是,我尝试定义一个名为 cout 的全局变量,然后在 main 中使用它,但编译器抱怨引用不明确。我不明白为什么。你能解释一下为什么我会出现这个错误吗?! 这是代码:
#include <iostream>
using namespace std;
int getInteger();
int cout;
int main()
{
int x{ getInteger() };
int y{ getInteger() };
cout = 20;
std::cout << x << " + " << y << " is " << x + y << '\n';
return 0;
}
int getInteger()
{
std::cout << "Enter an integer: ";
int x{};
std::cin >> x;
return x;
}
The error:
||=== Build: Debug in Chapter2_8 (compiler: GNU GCC Compiler) ===|
C:\CBProjects\Chapter2_8\main.cpp||In function 'int main()':|
C:\CBProjects\Chapter2_8\main.cpp|13|error: reference to 'cout' is ambiguous|
C:\Program Files\CodeBlocks\MinGW\lib\gcc\x86_64-w64-mingw32\8.1.0\include\c++\iostream|61|note: candidates are: 'std::ostream std::cout'|
C:\CBProjects\Chapter2_8\main.cpp|6|note: 'int cout'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
继续阅读下去。 “使用命名空间 std(以及为什么要避免它)”一章解释了
using namespace std;
的问题以及为什么它不允许您再使用 std
命名空间中的名称。
通过添加
using namespace std;
,您将命名空间 std
中的 all名称引入全局命名空间,现在编译器无法区分全局命名空间中的
int cout
和同样位于全局命名空间中的 std::ostream std::cout
,因为using namespace std;
。