一、模板类外实现
1.1 Number.h
#pragma once
#include <iostream>
using namespace std;
template<class T>
class Number {
public:
T add(T num1,T num2);
T sub(T num1,T num2);
};
1.2 Number.cpp
#include "Number.h"
template<typename T>
T Number<T>::add(T num1,T num2)
{
return num1 + num2;
}
template<typename T>
T Number<T>::sub(T num1, T num2)
{
return num1 + num2;
}
1.3 main.cpp
#include <iostream>
#include "Number.h"
int main()
{
system("pause");
return 0;
}
二、友元函数与类模板
2.1 template_and_friend.cpp
#include<iostream>
#include<string>
using namespace std;
template<class T> class Man;
template<class T> void printMan(Man<T> man);
template<class T>
class Man {
public:
template<class T>
friend ostream& operator<<(ostream& os, Man<T>& man);
friend void printMan<T>(Man<T> man);
Man(T age, T id);
void show();
static int number;
private:
T mId;
T mAge;
};
template<class T>
int Man<T>::number = 0;
template<class T>
Man<T>::Man(T age,T id)
{
mId = id;
mAge = age;
}
template<class T>
void Man<T>::show()
{
cout << "Age:" << mAge << " Id: " << mId << endl;
}
template<class T>
ostream& operator<<(ostream& os, Man<T>& man) {
os << "Age:" << man.mAge << " Id:" << man.mId << endl;
return os;
}
template<class T>
void printMan(Man<T> man)
{
cout << "Age:" << man.mAge << " Id:" << man.mId << endl;
}
void test_template_friend()
{
Man<int> man(100, 2);
printMan<int>(man);
}
void test_staic_member()
{
Man<int> man1(20,1);
Man<int> man2(21,2);
Man<float> man3(30, 1);
Man<float> man4(31, 2);
man1.number = 100;
man3.number = 200;
cout << "man1.number=" << man1.number << " man2.number=" << man2.number << endl;
cout << "man3.number=" << man3.number << " man4.number=" << man4.number << endl;
}
2.2 main.cpp
#include <iostream>
extern void test_template_friend();
extern void test_staic_member();
int main()
{
test_staic_member();
system("pause");
return 0;
}