This question already has answers here:
Why can templates only be implemented in the header file?
                                
                                    (16个答案)
                                
                        
                                4年前关闭。
            
                    
我试图弄清楚如何在类模板中使用类,但出现以下错误:

错误1错误LNK2019:未解析的外部符号“公共:__thiscall AdtBag :: AdtBag(void)”(?? 0?$ AdtBag @ H @@ QAE @ XZ)在函数_main C:\ Users \ User \ Documents \ Visual Studio中引用2013 \ Projects \ ADTBagAddition \ ADTBagAddition \ Source.obj ADTBagAddition

错误2错误LNK2019:在函数_main C:\ Users \ User \ Documents \ Visual中引用的未解析的外部符号“ public:__thiscall AdtBag ::〜AdtBag(void)”(?? 1?$ AdtBag @ H @@ QAE @ XZ) Studio 2013 \ Projects \ ADTBagAddition \ ADTBagAddition \ Source.obj ADTBagAddition

错误3错误LNK2019:未解析的外部符号“公共: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。我以为我做的一切都正确,但是我想没有。有什么建议么?

最佳答案

宽松地说,所有模板类代码都必须在标头中。

本质上,这是因为模板代码仅在为某种类型实例化模板时才编译。

关于c++ - 不会为C++创建类模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28972816/

10-11 21:08