我试图找出如何使用类模板的类,我得到这些错误:
错误1错误LNK2019:未解析的外部符号" public:__ thishisall AdtBag :: AdtBag(void)"函数_main C:\ Users \ User \ Documents \ Visual Studio 2013 \ Projects \ ADTBagAddition \ ADTBagAddition \ Source.obj ADTBagAddition
中引用了(?? 0?$ AdtBag @ H @@ QAE @ XZ)错误2错误LNK2019:未解析的外部符号" public:__ thishisall AdtBag :: ~AdtBag(void)"函数_main C:\ Users \ User \ Documents \ Visual Studio 2013 \ Projects \ ADTBagAddition \ ADTBagAddition \ Source.obj ADTBagAddition
中引用了(?? 1?$ AdtBag @ H @@ QAE @ XZ)错误3错误LNK2019:未解析的外部符号" public:void __thiscall AdtBag :: store_in_bag(int)" (?store_in_bag @?$ AdtBag @ H @@ QAEXH @ Z)在函数_main C:\ Users \ User \ Documents \ Visual Studio 2013 \ Projects \ ADTBagAddition \ ADTBagAddition \ Source.obj ADTBagAddition
中引用错误4错误LNK2019:未解析的外部符号" public:int __thiscall AdtBag :: whats_in_bag(void)" (?whats_in_bag @?$ AdtBag @ H @@ QAEHXZ)在函数_main C中引用:\ Users \ User \ Documents \ Visual Studio 2013 \ Projects \ ADTBagAddition \ ADTBagAddition \ Source.obj ADTBagAddition
错误5错误LNK1120:4个未解析的外部C:\ Users \ User \ Documents \ Visual Studio 2013 \ Projects \ ADTBagAddition \ Debug \ ADTBagAddition.exe ADTBagAddition
这是我的代码:
source.cpp
#include <iostream>
#include "AdtBag.h"
using namespace std;
int main () {
AdtBag<int> BagInt;
int a = 78;
cout << "Int Bag Contains: " << endl;
BagInt.store_in_bag ( a );
cout << BagInt.whats_in_bag () << endl;
return 0;
}
AdtBag.h
#ifndef __ADTBAG__
#define __ADTBAG__
template<class ItemType>
class AdtBag {
private:
ItemType in_bag;
public:
AdtBag<ItemType> ();
~AdtBag<ItemType> ();
void store_in_bag ( ItemType into_bag );
ItemType whats_in_bag ();
};
#endif
AdtBag.cpp
#include "AdtBag.h"
template <class ItemType>
AdtBag<ItemType>::AdtBag () {
}
template <class ItemType>
AdtBag<ItemType>::~AdtBag () {
}
template<class ItemType>
void AdtBag<ItemType>::store_in_bag ( ItemType into_bag ) {
in_bag = into_bag;
}
template<class ItemType>
ItemType AdtBag<ItemType>::whats_in_bag () {
return in_bag;
}
为什么会产生错误消息?如果重要的话,我正在使用Visual Studio 2013。我以为我做的一切都正确,但我猜不是。有什么建议吗?
答案 0 :(得分:3)
简而言之,所有模板类代码都必须在标题中。
基本上,这是因为只有在为某种类型实例化模板时才会编译模板代码。