C++ 72 之 友元和类模版

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

// 写法2:
// template<class T1, class T2>
// class Students12;

// 要提前用到Students12,需要在前面先让编译器见过Students12才可以
// template<class T1, class T2>
// void printStu(Students12<T1, T2>& stu);  // 此处不要加<> ,只让编译器提前见过这个代码,后续才能正常运行


// 3、类中声明友元,类外定义(让见过的代码和定义代码写在一起)
template<class T1, class T2>
class Students12;

template<class T1, class T2>
void printStu(Students12<T1, T2>& stu) {
	cout << "姓名:" << stu.m_name << endl;
	cout << "年龄:" << stu.m_age << endl;
}

// 此三种方法,尽量使用第一种。其他两种不太推荐使用

template<class T1,class T2>
class Students12 {
public:
	Students12(T1 name,T2 age) {
		this->m_name = name;
		this->m_age = age;
	}
	
	 //1、类中友元函数,在类外调用的时候,直接按照普通函数的调用方式即可,不用实例化后再调用
	//friend void printStu(Students12<T1, T2>& stu) {
	//	cout << "姓名:" << stu.m_name << endl;
	//	cout << "年龄:" << stu.m_age << endl;
	//}
	
	// 2、类中声明友元。类外定义,需要设置空模板参数列表
	// friend void printStu<>(Students12<T1, T2>& stu); 


	// 3、类中声明友元,类外定义(让见过的代码和定义代码写在一起)
	friend void printStu<>(Students12<T1, T2>& stu);

private:
	T1 m_name;
	T2 m_age;
};

 //2、类外定义,函数模板
//template<class T1, class T2>
//void printStu(Students12<T1, T2>& stu) {
//	cout << "姓名:" << stu.m_name << endl;
//	cout << "年龄:" << stu.m_age << endl;
//}




int main(void)
{
	Students12<string, int> stu("张三",200);

	//stu.printStu(stu);
	// 类中友元函数,在类外调用的时候,直接按照普通函数的调用方式即可,不用实例化后再调用
	printStu(stu);
	return EXIT_SUCCESS;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值