c++友元函数与模板类的使用

友元函数在模板类中的使用很繁琐,
从声明友元函数开始,就要声明虚拟类型,
然后并在声明友元函数的头放上虚拟参数列表,
之后的实现过程中也要加上虚拟列表

#include<iostream>
using namespace std;
template <typename T>
class A {
    
    
public:
	A(T t = 0);
	T getT();
	A operator+(const A& other);
	template <typename T>
	friend A<T> addA(const A<T>&a,const A<T> &b);
	//这里开始要写虚拟参数列表
private:
	T t;
};
template <typename T>
A<T> addA(const A<T> &a, const A<T> &b) {
    
    
	A<T> tmp;
	tmp.t = a.t + b.t;
	return tmp;
}
template <typename T>
A<T>::A<T>(T t) {
    
     
	this->t = t;
}
template <typename T>
T A<T>::getT() {
    
      
	return t;
}
template <typename T>
A<T> A<T>::operator+(const A<T>& other) {
    
    
	A tmp;
	tmp.t = this->t + other.t;
	return tmp;
}
int main() {
    
    
	A<int> a(20);
	A<int> b(10);
	A<int> tmp = addA<int >(a, b);
	cout << tmp.getT() << endl;
	system("pause");
	return 0;
}

结论:
(1)类内部声明友元函数,必须写成一下形式
template
friend A addA (A &a, A &b);

(2)友元函数实现 必须写成
template
A add(A &a, A &b)
{
//…
}
(3)友元函数调用 必须写成
A c4 = addA(c1, c2);

猜你喜欢

转载自blog.csdn.net/weixin_49324123/article/details/110306599