C++ 类模板的友元函数的类外实现

类模板的友元函数的类外实现

C++学习中看到视频课上的友元函数的类外实现不仅要在类内部声明友元函数是一个模板函数,还要在类外再去声明,并且由于友元函数的参数是一个模板类,还要类外声明模板类。
代码如下:

template<class T1, class T2>class Person;
template<class T1,class T2>void showPerson(Person<T1, T2>& p);

template<class T1, class T2>
class Person
{
     
public:
	Person(T1 age, T2 name) :m_age(age), m_name(name) {
     };
	
	friend void showPerson<>(Person<T1, T2>& p);


private:
	T1 m_age;
	T2 m_name;
};

template<class T1,class T2>
void showPerson(Person<T1, T2>& p)
{
     
	cout << p.m_name << "的年龄是:" << p.m_age << endl;

}
int main()
{
     

	Person<int, string> p(15, "小王");
	showPerson(p);

	return 0;
}

实际上,在类内声明友元函数是一个模板函数不就可以了吗

template<class T1, class T2>
class Person
{
     
public:
	Person(T1 age, T2 name) :m_age(age), m_name(name) {
     };
	template<class T1, class T2>
	friend void showPerson(Person<T1, T2>& p);


private:
	T1 m_age;
	T2 m_name;
};

template<class T1,class T2>
void showPerson(Person<T1, T2>& p)
{
     
	cout << p.m_name << "的年龄是:" << p.m_age << endl;

}

int main()
{
     

	Person<int, string> p(15, "小王");
	showPerson(p);



	
	return 0;
}

你可能感兴趣的:(C++,c++)