我对之前关于此的帖子有一些很好的了解,但我不知道这些编译错误意味着什么,我可以使用一些助手。模板、 friend 和重载都是新的,所以 3 合 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
点.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;
}
主要.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;
}
最佳答案
对于大多数编译器,您需要将模板放在 header 中,以便它们在使用它们的地方对编译器可见。如果你真的想避免这种情况,你可以在必要的类型上使用模板的显式实例化,但将它们放在标题中更为常见。
关于c++ - friend 、模板、重载 << 链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2970007/