我试图了解在 C++
中包含的工作原理.我有两个问题。第一个是关于如何正确导入 .h
文件。例如我创建了以下 HashNode.h
文件:
namespace HashNode{
template<class Data>
class HashNode{
private:
Data data;
HashNode *next;
public:
explicit HashNode(const Data &data);
Data getKey();
~Node();
};
}
所以在
HashNode.cpp
文件,它应该是:#include "HashNode.h"
using namespace HashNode;
template <class Data> // ~~~ HERE 1 ~~~
HashNode::HashNode(const Data &data) {//todo};
template <class Data> // ~~~ HERE 2 ~~~
Data* HashNode::getKey() {
//todo
}
HashNode::~Node() {
//todo
}
这样就可以了,但我是否必须包含
template <class Data>
在使用 Data
的每个函数旁边?为什么它不识别 Data
不包括 template <class Data>
?我也创建了
Hash.h
应该使用 HashNode.h
的文件文件:#include "HashNode.h"
using namespace HashNode;
namespace Hash {
template <class Data>
class Hash {
typedef enum {
GOOD = 0,
BAD = -1,
BAD_ALLOC = -2
} Status;
private:
HashNode **hash;
int capacity;
int size;
public:
explicit Hash(int size);
Status insertData(const Data &data);
~Hash();
};
}
但我收到以下错误:
Can't resolve type 'HashNode'
.为什么看不到导入?在
Hash.cpp
我得到的文件 Unused import statement
为 #include "HashNode.h"
.这是为什么?另外,如果我想包含私有(private)函数怎么办——它们应该在
.h
中吗?文件或在 .cpp
文件?
最佳答案
模板类的成员函数本身也是模板。因此,需要使用任何必需的模板参数和模板类型定义来定义它们。
关于你的第二个问题,它与命名空间有关。在我看来,命名空间和类在相同的命名下可能会导致歧义。尽管如此,在代码的结构方面似乎一切都很好。尝试使用 #pragma once
或某种保护措施来防止此类问题。
关于c++ - 了解导入在 C++ 中的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598187/