我不敢问为什么我需要在模板声明时在.cpp
末尾添加.h
。因为它已在StackOverflow中多次回答。
但我的问题是,为什么它不是循环依赖,或者编译器如何继续将.cpp
添加到.h
和.h
到.cpp
,当我在标题末尾添加.cpp?
C ++ 11是否试图解决这个奇怪的模板要求?
@Edit:仅包含标题文件
#ifndef MYMAP
#define MYMAP
#include <iostream>
#include <string>
using namespace std;
template<typename ValType>
class MyMap
{
public:
MyMap();
~MyMap();
void add(string key, ValType val);
ValType getValue(string key);
private:
static const int NumBuckets = 99;
struct cellT
{
string key;
ValType val;
cellT* next;
};
cellT *buckets[NumBuckets];
int hash(string key, int numBuckets);
cellT* findCellForKey(string key, cellT *head);
MyMap(MyMap&);
MyMap operator = (MyMap&);
};
#include "MyMap.cpp" //included .cpp
#endif
@Edit 2:MyMap.cpp
#include "MyMap.h"
//rest of the code
感谢。
答案 0 :(得分:5)
不考虑这种技术的优点,你问题中的代码因为包含守卫而起作用:
#ifndef MYMAP
#define MYMAP
...
#endif
第二次包含.h
时,由于第一次定义了MYMAP
,因此实际上是无操作。
P.S。不要在头文件中执行using namespace std
。包含此标头的任何代码都会将整个std
命名空间带入当前范围,而不管它们是否需要它。