重要更新:删除朋友的授权可以部分解决问题,但是为什么呢?以及如何保持它作为朋友...
为什么以下代码使我出现链接器错误?
Dimensions dims2(3 ,14);//Fixed class 100% the bug isn't cause by it
Matrix<int> mat_2(dims2, 5);
std::cout << mat_2;
我的课:
template<class T>
class Matrix {
public:
friend std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix);
;}
在.h
文件中我有:
template<typename T>
std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix) {}
我得到以下内容:
架构x86_64的未定义符号:
“ mtm :: operator <<(std :: __ 1 :: basic_ostream>&,mtm :: Matrix const&)”,引用自:main.cpp.o ld中的_main:未找到符号用于架构x86_64铛:错误:链接器命令失败,退出代码为1(使用-v查看调用)
friend std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix);
这声明了一个非模板函数,名为operator<<
(在命名空间中的Matrix
定义中)。该函数从未定义。此外,还operator<<
定义了一个功能模板。在进行重载解析时,编译器更喜欢使用非模板而不是模板,然后链接程序发现没有定义。
有几种解决方法。一种是在类中定义运算符:
template<class T>
class Matrix {
friend std::ostream& operator<<(std::ostream& os, const Matrix<T>& matrix) {
// Implementation here
}
};
另一个是与功能模板成为朋友:
template <typename T> class Matrix;
template<typename T>
std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix);
template<class T>
class Matrix {
friend std::ostream& operator<< <T>(std::ostream &os, const Matrix<T> &matrix);
};
第三,根本不需要友谊,例如:
template<class T>
class Matrix {
public:
// Actual implementation here.
void PrintMe(std::ostream &os);
};
template<typename T>
std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix) {
matrix.PrintMe(os);
return os;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句