前言:自從開始學模板了后,小編在練習的過程中。常常一編譯之后出現幾十個錯誤,而且還是那種看都看不懂那種(此刻只想一句MMP)。於是寫了便寫了類模板友元函數的用法這篇博客。來記錄一下自己的學習。
普通友元函數的寫法:
第一種:(直接上代碼吧)
#include <iostream> #include <string> using namespace std; template<class T> class Person{ public: Person(T n) { cout << "Person" << endl; this->name = n; } ~Person() { cout << "析構函數" << endl; } //友元函數 /********************************/ template<class T> friend void print(Person<T> &p); /*******************************/ private: T name; }; //友元函數 template<class T> void print(Person<T> &p) { cout << p.name << endl; } int main() { Person<string>P("XiaoMing"); print(P); system("pause"); return 0; }
第二種方法:
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 //方法二必不可缺的一部分 7 /**************************************/ 8 template<class T> class Person; 9 template<class T> void print(Person<T> &p); 10 /****************************************/ 11 template<class T> 12 class Person{ 13 public: 14 Person(T n) 15 { 16 cout << "Person" << endl; 17 this->name = n; 18 } 19 ~Person() 20 { 21 cout << "析構函數" << endl; 22 } 23 //友元函數 24 /********************************/ 25 friend void print<T>(Person<T> &p); 26 /*******************************/ 27 private: 28 T name; 29 }; 30 31 //友元函數 32 template<class T> 33 void print(Person<T> &p) 34 { 35 cout << p.name << endl; 36 } 37 38 39 40 int main() 41 { 42 Person<string>P("XiaoMing"); 43 print(P); 44 45 system("pause"); 46 return 0; 47 }
運算符重載中的友元函數:
方法一:
#include <iostream> #include <string> using namespace std; template<class T> class Person{ public: Person(T n) { cout << "Person" << endl; this->name = n; } ~Person() { cout << "析構函數" << endl; } //友元函數 /********************************/ template<class T> friend ostream& operator<<(ostream &os, Person<T> &p); /*******************************/ private: T name; }; //運算符重載 template<class T> ostream& operator<<(ostream &os, Person<T> &p) { os << p.name << endl; return os; } int main() { Person<string>P("XiaoMing"); cout << P << endl; system("pause"); return 0; }
方法二:
#include <iostream> #include <string> using namespace std; template<class T> class Person{ public: Person(T n) { cout << "Person" << endl; this->name = n; } ~Person() { cout << "析構函數" << endl; } //友元函數 /********************************/ //template<class T> friend ostream& operator<<<T>(ostream &os, Person<T> &p); /*******************************/ private: T name; }; //運算符重載 template<class T> ostream& operator<<(ostream &os, Person<T> &p) { os << p.name << endl; return os; } int main() { Person<string>P("XiaoMing"); cout << P << endl; system("pause"); return 0; }