目录
1.普通全局函数做类模板的友元函数
2.运算符重载做类模板的友元函数
1.普通全局函数做类模板的友元函数
需求:现有demo类模板,要求使用自定义addFun函数,实现对两个demo对象的相加
需求:现有demo类模板,要求使用自定义addFun函数,实现对两个demo对象的相加
demo.h
#pragma once #include#include using namespace std; template class A{ public: A(T t = 0); T getT(); template friend A addFun( const A a1, const A a2); private: T t; }; template A ::A(T t) { this->t = t; } template T A ::getT() { return t; }
类内部声明友元函数,必须写成以下形式:
template
friend A
addFun (A &a, A &b);
main.cpp
#include#include"A.h" template A addFun( const A a1,const A a2) { T temp =A ( a1.t * 2 + a2.t * 3); return A (T); } int main() { A a1(111), a2(222); A temp= addFun (a1,a2); cout << temp.getT() << endl; system("pause"); return 0; }
运行结果:
2.运算符重载做类模板的友元函数
需求:通过左移(<<)运算符号直接输出demo类模板。
需求:通过左移(<<)运算符号直接输出demo类模板。
demo.h
#pragma once #include#include using namespace std; template class A{ public: A(T t = 0); T getT(); template //注意在参数列表前要加 “<>” friend std::ostream& operator << <>(std::ostream& os, const A a); //重载加号运算符 A operator+(const A a2); private: T t; }; template A ::A(T t) { this->t = t; } template T A ::getT() { return t; } template A A ::operator+(const A a2) { A temp = A (this->t + a2.t); return A (temp.t); }
关于重载运算符作类模板友元函数,在参数列表前加“<>” :
一是,表明此友元函数是函数模板;
二是,此模板使用的模板类型参数为当前模板类的类型参数class
main.cpp
#include#include"A.h" template std::ostream& operator << (std::ostream & os, const A a) { stringstream s; s << "总和为:" << a.t ; cout << s.str(); return os; } int main() { A a1(111), a2(222); A temp= a1+a2; std::cout << temp.getT() << std::endl; system("pause"); return 0; }
运行结果:



