编程语言
首页 > 编程语言> > C++ 学习之类模板与友元 (全局函数类内、类外实现)

C++ 学习之类模板与友元 (全局函数类内、类外实现)

作者:互联网

1、全局函数类内实现:

#include<iostream>
#include<string>
using namespace std;

template<class T1, class T2>
class Person
{
	//1、全局函数配合友元类内实现
	friend void ShowPerson(Person<T1, T2>& p)//全局函数访问类内成员,直接写在类内即可
	{	
		cout << "姓名:" << p.m_name << " " << "年龄:" << p.m_age << endl;
	}

public:
	Person(T1 name, T2 age);//默认构造函数声明

private:

	T1 m_name;
	T2 m_age;

};

template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)//类外构造函数实现
{
	this->m_name = name;
	this->m_age = age;
}

int main()
{
	Person<string, int> p("孙悟空", 100);
	ShowPerson(p);
	
	return 0;
}

2、全局函数类外实现:

#include<iostream>
#include<string>
using namespace std;


//用到了Person这个数据类型,提前声明
template<class T1, class T2>
class Person;


//函数的定义要写在类前面,提前让编译器知道,写在类的后边就无法识别了
template<class T1, class T2>
void ShowPerson(Person<T1, T2>& p)
{
	cout << "姓名:" << p.m_name << " " << "年龄:" << p.m_age << endl;
}


template<class T1, class T2>
class Person
{
	//1、全局函数配合友元类内实现
	//friend void ShowPerson(Person<T1, T2>& p)//全局函数访问类内成员,直接写在类内即可
	//{	
	//	cout << "姓名:" << p.m_name << " " << "年龄:" << p.m_age << endl;
	//}


	//2、全局函数类内声明,类外实现
	friend void ShowPerson<>(Person<T1, T2>& p);//注意加 < >



public:
	Person(T1 name, T2 age);//默认构造函数声明

private:

	T1 m_name;
	T2 m_age;

};

template<class T1, class T2>
Person<T1, T2>::Person(T1 name, T2 age)//类外构造函数实现
{
	this->m_name = name;
	this->m_age = age;
}



int main()
{
	Person<string, int> p("孙悟空", 100);
	ShowPerson(p);
	
	return 0;
}

总结:
建议全局函数做类内实现,用法简单,而且编译器可以直接识别

标签:友元,name,age,C++,Person,类外,类内,全局,函数
来源: https://blog.csdn.net/weixin_44618297/article/details/120763104