这个问题有很多解决方案,但没有一个能回答我的问题。
我正在使用 VS 2008。我正在尝试使用二叉搜索树创建 map
#ifndef _map_h
#define _map_h
#include<string>
using namespace std;
template <typename ValType>
class Map
{
public:
Map();
~Map();
ValType getvalue(string key);
void add(string key,ValType value);
private:
struct node{
string key;
ValType value;
node *right;
node *left;
};
node *root;
node *treeSearch(string key,node *t);
void treeEnter(string key,ValType value,node *&t);
};
#include"map.cpp"
#endif
map .cpp
#include<string>
#include<iostream>
#include"map.h"
using namespace std;
template <typename ValType>
Map<ValType>::Map(){
root=NULL;
}
template <typename ValType>
Map<ValType>::~Map(){
delete root;
}
template <typename ValType>
ValType Map<ValType>::getvalue(string key){
node *found=treeSearch(key,root);
if(found==NULL)
cout<<"Couldnot Found the node";
else return found->value;
}
template <typename ValType>
typename Map<ValType>::node *Map<ValType>::treeSearch(string key,node *t){
if(t==NULL) return NULL;
if(t->key==key) return t;
if(t->key>key) treeSearch(key,t->left);
else treeSearch(key,t->right);
}
template <typename ValType>
void Map<ValType>::add(string key,ValType value){
treeEnter(key,value,root);
}
template <typename ValType>
void Map<ValType>::treeEnter(string key,ValType value,node *&t){
if(t==NULL){
t->value=value;
t->key=key;
t->left=NULL;
t->right=NULL;
}
else if(t->key==key) t->value=value;
else if(t->key>key) treeEnter(key,value,t->left);
else treeEnter(key,value,t->right);
}
错误:对于所有的函数,它都说它们已经被定义了。
我正在学习斯坦福在线类(class)并且同样适用于讲师(她使用的是 mac)
最佳答案
您已将 map.h
包含到 map.cpp
中,将 map.cpp
包含到 map.h
中。 map.h
中的包含保护将防止多次包含 map.h
并将防止无限递归包含。但是,如果您将 map.cpp
直接提供给编译器(这显然是您正在尝试做的),它将包含一次 map.h
然后 map .h
将再次包含 map.cpp
本身。这就是导致错误的原因。
如果您想将模板实现为包含在.h
文件中的.cpp
文件,您可以这样做。这很奇怪,但它可以被强制工作。首先,如果您决定#include
您的map.cpp
,那么甚至不要尝试编译您的map.cpp
。不要将您的 map.cpp
直接提供给编译器。此外,从该 .cpp
文件中删除 #include "map.h"
。这样做绝对没有意义。
您的程序将有其他实现文件,比如 myprogram.cpp
,它将使用您的 map 。 myprogram.cpp
应该包含 map.h
。 myprogram.cpp
就是您要提供给编译器的内容。这样它就会按预期工作。但是尝试直接编译 map.cpp
只会导致错误。
不过,更好的办法是不要将任何内容放入 .cpp
文件中。要么将所有内容放入 .h
文件,或者,如果您真的希望以这种方式拆分它,请将您的 .cpp
文件重命名为其他名称,以便让每个人都清楚这不是翻译单位。
关于c++ - 错误 C2995 :function template has already been defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17512915/