首页 > 解决方案 > C++ std:: 并包括它们如何组合在一起?

问题描述

我很困惑。我编写了一个名为 hash() 的函数,我使用命名空间 std 来表示 cout、endl 和 laziness。

对“哈希”的错误引用不明确

我现在知道 std:: 中存在哈希函数

所以我的问题是为什么编译器会抛出这个错误,因为我从来没有包含functional.h?

是否有来自 std:: 名称的索引,以便将来在编写自己的函数时可以避免使用这些名称,我在谷歌上找不到任何东西?

我很困惑,因为当 std:: 中的“一切”都知道时,为什么需要包含标题?我确定我错过了什么

也许我的头衔不是最好的,但我不知道更好。

#include <iostream>
using namespace std;

const int SIZE_TABLE = 10;

int hash(int x)
{
    return x%SIZE_TABLE;
}

int main()
{
    cout<<"hash 24 "<<hash(24)<<endl;
    return 0;
}

标签: c++includestd

解决方案


The compiler try to get the right hash function. Your hash function is implemented under the global namespace, addressed with ::

::hash(1)

In normal cases the compiler would use this namespace, if you call it with

hash(1)

But you say to the compile "hey dude, search every call also in std::" with:

using namespace std;

so he cant decide between

::hash(1)
and
std::hash(1)

using in global scope is a problem in header files, because you import this directive to other files, which include your header file.

In a cpp files, this is matter of taste. I prefer not to use it in cpp, also.


推荐阅读