1

これに関する以前の投稿で良い洞察を得ましたが、これらのコンパイル エラーが何を意味し、アシスタントを使用できるのかわかりません。テンプレート、フレンド、オーバーロードはすべて新しいため、3 in 1 はいくつかの問題を引き起こしています...

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Point<double>::Point<double>(double,double)" (??0?$Point@N@@QAE@NN@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Point<int>::Point<int>(int,int)" (??0?$Point@H@@QAE@HH@Z) referenced in function _main
1>C3_HW8.exe : fatal error LNK1120: 3 unresolved externals

Point.h

#ifndef POINT_H
#define POINT_H

#include <iostream>

template <class T>
class Point
{
public:
 Point();
 Point(T xCoordinate, T yCoordinate);
 template <class G>
 friend std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint);

private:
 T xCoordinate;
 T yCoordinate;
};

#endif

ポイント.cpp

#include "Point.h"

template <class T>
Point<T>::Point() : xCoordinate(0), yCoordinate(0)
{}

template <class T>
Point<T>::Point(T xCoordinate, T yCoordinate) : xCoordinate(xCoordinate), yCoordinate(yCoordinate)
{}


template <class G>
std::ostream &operator<<(std::ostream &out, const Point<G> &aPoint)
{
 std::cout << "(" << aPoint.xCoordinate << ", " << aPoint.yCoordinate << ")";
 return out;
}

main.cpp

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

int main()

    {
     Point<int> i(5, 4);
     Point<double> *j = new Point<double> (5.2, 3.3);
     std::cout << i << j;
    }
4

2 に答える 2

5

ほとんどのコンパイラでは、テンプレートをヘッダーに配置する必要があります。これにより、テンプレートが使用されているコンパイラに表示されます。本当にそれを避けたい場合は、必要な型に対してテンプレートの明示的なインスタンス化を使用できますが、それらをヘッダーに配置する方がはるかに一般的です。

于 2010-06-03T21:48:31.123 に答える
0

Point クラスは、メイン関数と同じプロジェクト内で定義およびコンパイルされていますか? テンプレートはコンパイル時に解決されるため、静的ライブラリなどの 2 番目のプロジェクトでテンプレートを定義して、それに対してリンクすることはできません。別のプロジェクトでそれが必要な場合は、ヘッダー内に完全な実装を提供し、テンプレートのソース ファイルを単に省略する必要があります。そのヘッダーを含めると、メイン関数を含むファイルがコンパイルされると、テンプレートは実際のインスタンス化用にコンパイルされます。この場合、ポイントとポイントです。

このクラスを使用するにはリンクが必要であり、テンプレート ヘッダーのみで構成されるプロジェクトではリンク可能なライブラリが生成されないことに注意してください。

于 2010-06-03T23:52:34.673 に答える