2015-10-21 25 views
0

嗨,我有一个代码,其结构解释如下。这不是实际的代码,但我试图模拟这个问题,它给出了同样的错误。'unordered_set'在声明头文件时没有指定类型

我有一个名为classTest.cpp文件,其中包含:

#include<iostream> 
#include "header.h" 

using namespace std; 
int main() 
{ 
    test f; 
    f.insert(10); 
    cout<<f.search(10)<<endl; 
    return 0; 
} 

header.h包含以下代码:

#include<unordered_set> 
class test 
{ 
    public: 
    int apple; 
    unordered_set<int> set; 
    bool search(int a); 
    void insert(int a); 
}; 
bool test::search(int a) 
{ 
    if(apple!=a) 
     return false; 
    return true; 
     /* 
    if(set.find(a) == set.end()) 
     return false; 
    return true;*/ 
} 


void test::insert(int a) 
{ 
    apple = a; 
    //set.insert(a); 
} 

当我编译classTest.cpp我收到以下错误:

header.h:6:2: error: ‘unordered_set’ does not name a type 
    unordered_set<int> set; 

但是,当我复制header.h内容并将其粘贴到classTest.cpp它工作正常。我无法理解原因。有一些我错过的基本概念吗?

+2

你包括它之前* *在'使用命名空间std;',但(显然)当您粘贴它,你把它之后。将其更改为标题中的“std :: unordered_set”,并查看事情是否有效。 –

+2

改为使用'std :: unordered_set'。因为你似乎并不知道'using namespace std;'的作用:只需停止使用它,并用'std ::'限定名称。 –

+0

哦!这是如此愚蠢的错误。现在工作。 – mribot

回答

0

正如评论中所述:您正试图使用​​unordered_set而不限定它来自的命名空间。因此你的编译器不知道它是什么类型。

当您复制的test声明为classTest.cpp因为该文件有一个using namespace std这工作。

你应该always qualify your types with their namespace(如果没有其他原因,以避免这样的问题)。在这种情况下,解决你的问题,你应该写:

std::unordered_set<int> set; 
+0

感谢您的回答。这是一个愚蠢的错误。我认为std ::不需要,因为我指定的命名空间,但错过了排序。但是,现在已经解决了。我在使用namespace std之后移动了导入标题。 – mribot