c++ - friend 、模板、重载 << 链接器错误

标签 c++ templates friend

我对之前关于此的帖子有一些很好的了解,但我不知道这些编译错误意味着什么,我可以使用一些助手。模板、 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/

相关文章:

c++ - Github 错误识别项目中使用的编程语言

c++ - 带有 std::enable_if 和 std::is_default_constructible 的 SFINAE 用于 libc++ 中的不完整类型

c++ - 派生类模板化时访问基本成员数据错误

c++ - C++ friend 模板函数:找不到函数定义

c++ - 模板类中的友元函数

c++ - 如何访问类成员

c++ - 当我使用回调函数访问成员变量时出现段错误

c++ - Old school Win32 Message Only 窗口无法接收消息

c++ - ffmpeg转OpenGL纹理黑屏

c++ - 模板:我需要更好地学习这些吗?为什么我收到错误