//class template and friend function#include <iostream>using namespacestd;template<typename t>classcomplex{ Public: Complex (T a,t b); voidPrint ()Const//The const modifier is the this pointer{cout<< This->real <<":"<< This->image<<Endl; } /*Emphasis: the implementation of the friend function in the class template can not be written in the outside of the class, can only be implemented within the class, or the compiler error is essentially because the class template compiled 2 times, resulting in the friend function has been compiled 2 times so the C + + compiler does not recognize the class template is written outside the friend function for the ordinary class is not A question */ //friend functionFriend Complexoperator+ (Complex &c1, Complex &C2) {Complex TEMPC (c1. Real+ c2. Real, C1. Image +C2. Image); returnTEMPC;//Anonymous Objects } //member functions---member functions are different from friend functions, and can be implemented outside the classComplexoperator-(Complex &C2);Private: T Real, Image;}; Template<typename t>Complex<T>:: Complex (t A, T b) { This->real =A; This->image =b;} Template<typename t>Complex<T> Complex<t>::operator-(Complex<t> &C2) {Complex TEMPC ( This->real-c2. Real, This->image-C2. Image); returnTEMPC;//Anonymous Objects}voidProtecta () {Complex<int> C1 (3,4); //C1. Print ();complex<int> C2 (5,7); //operator overloading + friend function implementationcomplex<int> c3 = C1 +C2; C3. Print (); /*first admit that the operator overload is a function, write out function name operator+ and then write out the argument list operator+ (complex<int> &c1,Complex<int> &am) based on the operand. P;C2) Finally the return value is determined based on the receiving object, implementing the function Complex<int> operator+ (complex<int> &c1,Complex<int> &c2) within the class Department can omit the argument list because the class declaration does not allocate memory and does not need to determine the size of the class*/Complex<int> c4 = c2-C1; /*first, it admits that operator overloading is a class intrinsic function, writes out the function name operator-and then writes out the parameter list c1.operator-(complex<int> &c2) according to the operands; Finally, the return value is determined according to the receiving object, and the function complex<int> c1.operator-(complex<int> &c2) is implemented. The argument list can be omitted inside the class because the class declaration does not allocate memory and does not need to determine the size of the class*/C4. Print (); }voidMain () {protecta (); System ("Pause");}
C + + class template Two (class templates and friend functions)