类模板类内实现,类外实现使用友元

// 类模板.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
//类内实现
template<class T1,class T2>
class Person {
public:
	T1 mName;
	T2 mAge;
	Person(T1 name, T2 age)
	{
		this->mAge = age;
		this->mName = name;

	}
	void show()
	{
		
		cout << "name"<<this->mName<<"age"<<this->mAge<<endl;
	}
};
void test01()
{
	Person<string, int> p("aaa", 10);
	p.show();
}
int main()
{
	test01();
    return 0;
}


类模板类外实现不要滥用友元

// 类模板.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
//法二2
template<class T>class Person;
template<class T>void print(Person<T>& p);

template<class T>
class Person {
public:
	Person(T age, T id);
	   //法一 重载左移操作符
	   //template<class T>
	  //  friend ostream& operator<<(ostream & os, Person<T> & p);
	   //法二
	   friend ostream& operator<<<T>(ostream & os, Person<T> & p);
	   //法一1  普通友元函数
	   //template<class T>
	  // friend void print(Person<T>& p);
	   friend void print<T>(Person<T>& p);
	   void show();
	
private:
	T mAge;
	T mID;
};
template<class T>
ostream& operator<<(ostream & os, Person<T> & p)
{
	cout << "age" << p.mAge << "id" << p.mID << endl;
	return os;
}

template<class T>
Person<T>::Person(T age, T id)
{
	this->mAge = age;
	this->mID = id;
}


template<class T>
void Person<T>::show()
{
	cout << "age" << mAge << "id" << mID << endl;

}


template<class T>
void print(Person<T>& p)
{

	cout <<"print"<< p.mAge << p.mID << endl;
}
void test01()
{
	Person<int> p(10, 20);
	//p.show();
	//cout << p;
	print ( p );
}
int main()
{
	test01();
    return 0;
}


发布了35 篇原创文章 · 获赞 2 · 访问量 2412

猜你喜欢

转载自blog.csdn.net/weixin_41375103/article/details/104566060