0

テンプレートメソッドを作成できることを読みました。コードにこのようなものがあります

ファイル : Student.h

class Student
{
public:
    template<class typeB> 
    void PrintGrades();
};

ファイル: Student.cpp

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

template<class typeB> 
void Student::PrintGrades()
{
    typeB s= "This is string";
    std::cout << s;
}

今main.cppにあります

Student st;
st.PrintGrades<std::string>();

今、私はリンカーエラーを受け取ります:

Error   1   error LNK2019: unresolved external symbol "public: void __thiscall Student::PrintGrades<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >(void)" (??$PrintGrades@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Student@@QAEXXZ) referenced in function _main

私が間違っているかもしれないことについて何か提案はありますか?

4

1 に答える 1

1

テンプレートがどこにもインスタンス化されていないため、リンカー エラーが発生します。

ヘッダーで定義されたテンプレートの場合、コンパイラはその定義にアクセスできるため、それ自体でインスタンス化を生成します。ただし、.cpp ファイルで定義されたテンプレートの場合は、自分でインスタンス化する必要があります。

次の行を .cpp ファイルの末尾に追加してみてください。

template void Student::printGrades<std::string>();
于 2013-10-06T19:50:12.690 に答える