调用operator <<时链接器错误,如何解决?

线

重要更新:删除朋友的授权可以部分解决问题,但是为什么呢?以及如何保持它作为朋友...

为什么以下代码使我出现链接器错误?

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查看调用)

伊戈尔·坦德尼克(Igor Tandetnik)
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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何解决“铛:错误:链接器命令失败,退出代码为1(使用-v查看调用)”错误?

如何解决链接器命令失败,退出代码为1(使用-v查看调用)

如何解决onReceive方法调用的此Swift编译器错误?

调用 google firebase api 时出现以下错误。如何解决这个问题

如何解决在调用View Controller时IBOutlet配置和UI不显示的nil错误?

使用模式实验室时,如何解决最大调用堆栈大小超出的错误?

使用zip()函数时如何解决以下错误?TypeError:“列表”对象不可调用

调用pthread_create时如何解决偶发的EINVAL错误

在链表实现中调用strcpy()时如何解决分段错误?

使用Python ctypes调用rs232.c时如何解决分段错误问题?

尝试通过 Web api 调用下载文件时,如何解决“发送 HTTP 标头后服务器无法设置状态”错误?

调用wmi时如何解决缓慢的加载时间(仅处理器)

如何解决链接器错误?

如何解决链接器命令失败,退出代码 1(使用 -v 查看调用)在 Xcode 10 中

如何解决意外的“->”(T_OBJECT_OPERATOR)错误?

尝试将C ++与Assembly链接时,如何解决此链接器错误?

如何解决从本机代码调用 java 方法时传递给 JNI 错误的全局或本地引用错误

保存地址时出现问题 - 错误“在构建期间调用了 setState() 或 markNeedsBuild()”。如何解决这个错误?

如何解决此错误“在构建期间调用setState()或markNeedsBuild()”?

如何解决错误“元组”对象不可调用

错误:无效的钩子调用我该如何解决?

如何解决“尝试调用方法'addMoney'(nil值)”错误?

如何解决此错误“方法'/'被调用为空”

如何解决调用方法c#的库错误?

如何解决:(类型错误:“str”对象不可调用)

如何解决“int”对象不可调用错误

如何解决IIS中的“在ISAPI筛选器“ C \ .. \ php5.dll上调用GetProcAddress”失败”错误?

getter 'length' 被调用为 null。接收器:空。如何解决列表列表的这个错误?

从基类继承两次时如何解决“错误:没有匹配的函数可调用”