在vs2017下编译通过。
#include "stdafx.h"
#include "iostream"
using namespace std;
//模板类的友元函数需要类的前置声明和函数的前置声明
template<typename T>
class Complex;
template<typename T>
Complex<T> myAdd(Complex<T>&c1, Complex<T> &c2);
template<typename T>
class Complex {
public:
Complex(T t1 , T t2) {
this->t1 = t1;
this->t2 = t2;
}
//声明一个友元函数
friend Complex myAdd<T>(Complex &c1 , Complex &c2);
//声明两个变量,为了测试方便声明为public访问类型
T t1;
T t2;
};
template<typename T>
Complex<T> myAdd(Complex<T> &c1, Complex<T> &c2) {
Complex<T> tmp(c1.t1 + c2.t1 , c1.t2 + c2.t2); //此处类型需要加上泛型
return tmp;
}
int main()
{
Complex<int>c = myAdd(Complex<int>(1,2),Complex<int>(4,3));
cout << c.t1 << endl;
system("pause");
return 0;
}
3553

被折叠的 条评论
为什么被折叠?



