有关模板的友元函数记录

有关模板的友元函数记录

  1. 错误信息如下
matrix.h:10:56: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, const matrix<T>&)’ declares a non-template function [-Wnon-template-friend]
  friend ostream& operator<< (ostream&, const matrix<T>&);

在CSDN上找到 这篇博客,然后根据这篇博客进行修改 https://blog.csdn.net/qq_37341466/article/details/81626193

  1. 首先按照“模板类的约束模板友元”类型更改,原来的写法是“非模板友元”
friend ostream& operator<< <>(ostream&, const matrix<T>&);   

之后出现 如下错误

matrix.h:10:18: error: template-id ‘operator<< <>’ for ‘std::ostream& operator<<(std::ostream&, const matrix<int>&)’ does not match any template declaration
  friend ostream& operator<< <>(ostream&, const matrix<T>&);

这个错误是因为我之前没有申明这个友元函数,所以不能或爆出这个错误。
之后在类声明之前加入如下语句

template <class T>
class matrix;

template <class T>
ostream& operator<<(ostream&, const matrix<T>&); 

之前的错误就直接消失了

总结
  1. 在调用模板的类的友元函数时,需要在函数名后面加一个 < > 将友元函数变成__模板类的约束模板友元__
  2. 使用友元函数的时候需要在类外部进行声明,不然会出现__错误2__
  3. 参考博客中的第三类友元函数:模板类的非约束模板友元,在类的内部声明友元,每个模板函数(类)具体化都是每个类具体化的友元,对于非约束友元,友元模板类型参数与模板类型 参数是不同的
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值