友元函数:解决从外部函数访问类的内部私有或保护数据。
模板友元函数:需要注意在定义中需要加上完整申明。
#include <iostream>using namespace std;
template <typename T>class Complex
{
protected:
T real, imag;
public:
Complex(T real_init, T imag_init) : real(real_init), imag(imag_init) {}
public:
template <typename U> friend U get_real(Complex<U>& c); //不能缺少,否则不能编译通过
template <typename U> friend U get_imag(Complex<U>& c);
};
template <typename U>U get_real(Complex<U>& c)
{ return c.real;}
template <typename U>U get_imag(Complex<U>& c)
{ return c.imag;}
int main()
{
Complex<int> a(1, 2);
cout<< get_real(a) <<endl;
cout<< get_imag(a) <<endl;
}