朋友,模板,重载<<链接器错误
我对之前的一篇关于此问题的文章有一些很好的见解,但我不知道这些编译错误意味着我可以使用一些助手。模板、朋友和重载都是新的,所以三合一给我带来了一些问题...
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
Point.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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于大多数编译器,您需要将模板放入标头中,以便使用它们的编译器可以看到它们。如果您确实想避免这种情况,可以在必要的类型上使用模板的显式实例化,但将它们放在标头中更为常见。
With most compilers, you need to put templates in headers, so they're visible to the compiler where they're used. If you really want to avoid that, you can use explicit instantiation of the template(s) over the necessary types, but putting them in a header is much more common.
Point 类是否与 main 函数在同一个项目中定义和编译?由于模板在编译时解析,因此您无法在第二个项目(例如静态库)中定义模板并链接到它。如果您希望将其放在单独的项目中,则需要在标头内提供完整的实现,并只需省略模板的源文件。包含该标头后,当编译具有主函数的文件时,将针对其实际实例(在您的情况下为 Point 和 Point)编译模板。
请记住,这确实需要任何链接才能使用该类,并且仅由模板头组成的项目无论如何都不会生成可链接的库。
Is the Point class defined and compiled inside the same project as the main function? As templates are resolved at compile time, you cannot define a template in a second project, for example a static lib, and link against it. If you want it in a seperate project, you need to provide the full implementation inside the header and simply omit the template's source file. Upon including that header, when the file with your main function is compiled, the template will be compiled for its actual instantiations, in your case Point and Point.
Keep in mind this does required any linking in order to use the class, and a project consisting of template headers only would not produce a linkable lib anyway.