簡體   English   中英

C ++:類模板,鏈接器錯誤和未解析的符號

[英]C++ : Class templates, linker errors, and unresolved symbols

我使用模板遇到了以下問題(我的IDE是Visual Studio 2012):

當我嘗試構建項目時,出現“無法解析的外部符號”鏈接器錯誤。 我讀到應該在頭文件中定義所有內容,而不是將我的類放在頭文件和源文件之間。 但是,它仍然無法正常工作。

在下面的示例中,我嘗試為“字典”創建類模板。 如果要使用它們的公共索引,則應該選擇一個類型和另一個類型,並使用兩個數組創建一個“單詞”到“單詞”的翻譯。 (盡管“字”不是確切的描述,即IE:input [0] ='A',output [0] = 2.5-這意味着'A'的定義為2.5)

這是我的代碼:

#include <iostream>
using namespace std;
#ifndef WORD_H
#define WORD_H


template <class w, class d>
class Dictionary
{
public:

     Dictionary() ;//{}; // constructor (default)
    ~Dictionary() ;//{}; // destructor

    void Define(const w &st,const d &nd)
    {
        if(index < 100)
        {
            input[index] = st;
            output[index++] = nd;
        }
        else
        {
            cerr<<"Not enough space in dictionary.";
        }
    }// Define words using 2 parameters.st represents input, nd represents output (word -> translation)

    void print_words()
    {
        for(int i = 0; i < index ; i++)
        {
            cout<<index<<". "<<input[i]<<output[i]<<endl;
        }
    }

private:
    w input[100];
    d output[100];
    static int index;
};
template <class w, class d>
int Dictionary<w,d>::index = 0;
#endif

“主”文件很簡單:

#include "Word.h"
#include <iostream>

void main()
{
    Dictionary<int,double> a;
    a.Define(5,5.5);
}

這些是錯誤:

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Dictionary<int,double>::Dictionary<int,double>(void)" (??0?$Dictionary@HN@@QAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Dictionary<int,double>::~Dictionary<int,double>(void)" (??1?$Dictionary@HN@@QAE@XZ) referenced in function _main

我該怎么做才能修復我的代碼?

 Dictionary() ;//{}; // constructor (default)
~Dictionary() ;//{}; // destructor

聲明默認的構造函數和析構函數,但不要定義它們。 也就是說,您告訴編譯器您正在編寫這些函數,因此它會繼續尋找它們,但實際上您尚未編寫它們,因此會感到不安。

您的選擇是(基本上都是一樣的):

  • 完全刪除這些行,並由編譯器生成它們
  • 刪除第一個注釋斜杠,並使用一個空的定義( Dictionary(){}; // blah
  • 如果您有最新的編譯器(支持C ++ 11),請使用default關鍵字: Dictionary() = default;

另外,在標頭中,文件的所有內容都應位於保護范圍內( includeusing )。 我強烈建議您不要using namespace std; 在頭文件中(我更喜歡根本不使用它)。 請參閱為什么“使用命名空間標准”被認為是不良做法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM