0
2つのデータ型T1とT2を使用するテンプレートクラスがあり、メソッド表示を使用して2つの異なるデータ型を取り込み、それらを端末に出力することになっています()C++ '未定義リファレンス'複数のデータ型を持つテンプレートクラス
pair.h
#ifndef PAIR_H
#define PAIR_H
template <class T1, class T2>
class Pair
{
public:
Pair();
Pair(const T1 & t1, const T2 & t2) : first(t1), second(t2) {}
~Pair();
T1 getFirst() const {return first;}
T2 getSecond() const {return second;}
void setFirst(const T1 & t1) {this->first = t1;}
void setSecond(const T2 & t2) {this->second = t2;}
void display()
{
std::cout << first << " - " << second << endl;
}
private:
T1 first;
T2 second;
};
#endif // PAIR_H
クラスはない.cppファイルとヘッダファイル "pair.h" で定義されています。私はペアクラスの新しいオブジェクトを作成しようとすると、私はエラーを取得:
Undefined reference to 'Pair<string, string>::Pair()'
Undefined reference to 'Pair<int, int>::Pair()'
Undefined reference to 'Pair<string, int>::Pair()'
Undefined reference to 'Pair<string, string>::~Pair()'
Undefined reference to 'Pair<int, int>::~Pair()'
Undefined reference to 'Pair<string, int>::~Pair()'
私は
main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "pair.h"
int main()
{
...
Pair<string, string> fullName;
fullName.setFirst(first);
fullName.setSecond(last);
fullName.display();
...
Pair<int, int> numbers;
numbers.setFirst(num1);
numbers.setSecond(num2);
numbers.display();
...
Pair<string, int> grade;
grade.setFirst(name);
grade.setSecond(score);
grade.display();
...
}
のようにmain()関数でそれを呼び出すクラスのデフォルトコンストラクタを呼び出すとこれは学校の割り当てのためにあるので
The makefile:
a.out : check11b.cpp pair.h
g++ check11b.cpp
、唯一のルールがあることメイクとmain.cppファイルは変更できません。 助けてください?
@MajidAbdolshahこれは完全に間違っています。ヘッダーファイルにすべての実装が含まれている場合、別の ".cpp"ファイルは必要ありません。テンプレートはヘッダファイルに完全に実装する必要があります。実装を別のファイルに移動することはできません。 – UnholySheep
@UnholySheep確かに、あなたは正しいです。私はこれを見た:https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file –