模板类中的友元函数使用注意
来源:互联网 发布:软件可行性方案模板 编辑:程序博客网 时间:2024/06/16 00:32
<pre name="code" class="cpp">#ifndef TEMPLATETEST_H#define TEMPLATETEST_H#include <iostream>#include <string>using namespace std;class myException{ public: myException(string s):info(s){}; string info;};template<class T> class Point;//模板类前置声明template<class T> istream& operator >> (istream& in,Point<T>& p); //声明友元模板函数template<class T> ostream& operator << (ostream& out,Point<T> p);template<class T>class Point{ public: Point():x(0),y(0){}; Point(T x,T y):x(x),y(y){}; void setX(T a); void setY(T a); T getX(); T getY(); ~Point(){}; Point operator+(Point& p); Point operator-(Point& p); Point operator*(T a); Point operator/(T a); friend istream& operator >> <>(istream& in,Point<T>& p); //注意在友元函数后加<>,一是,表明此友元函数是函数模板;二是,此模板使用的模板类型参数为当前模板类的类型参数class。 friend ostream& operator << <>(ostream& out,Point<T> p); private: T x; T y;};void templateTry();#endif // TEMPLATETEST_H
方法实现:
#include "templateTest.h"template<class T> void Point<T>::setX(T a){this->x=a;}template<class T> void Point<T>::setY(T a) {this->y=a;}template<class T> T Point<T>::getX(){return this->x;}template<class T> T Point<T>::getY(){return this->y;}template<class T> Point<T> Point<T>::operator+(Point& p){ Point<T> result; result.setX(this->x+p.x); result.setY(this->y+p.y); return result;}template<class T> Point<T> Point<T>::operator-(Point& p){ Point<T> result; result.setX(this->x-p.x); result.setY(this->y-p.y); return result;}template<class T> Point<T> Point<T>::operator*(T a){ Point<T> result; result.setX(this->x*a); result.setY(this->y*a); return result;}template<class T> Point<T> Point<T>::operator/(T a){ Point<T> result; if(0==a) { throw(new myException("Point operator / ,can not divice zero!")); } result.setX(this->x/a); result.setY(this->y/a); return result;}template<class T> istream& operator>>(istream& in,Point<T>& p){ T a,b; in>>a>>b; p.setX(a); p.setY(b); return in;}template<class T> ostream& operator<<(ostream& out,Point<T> p){ return out<<"("<<p.getX()<<","<<p.getY()<<")";}void templateTry(){ try{ Point<float> a(3,3),b; cin>>b; cout<<"a:"<<a<<endl; cout<<"b:"<<b<<endl; cout<<"a+b:"<<(a+b)<<endl; cout<<"a-b:"<<(a-b)<<endl; cout<<"a*100:"<<(a*100)<<endl; cout<<"a/20:"<<(a/20)<<endl; } catch(myException* e) { cout<<e->info<<endl; }}运行结果:
0 0
- 模板类中的友元函数使用注意
- 模板类中的友元函数写法
- c++模板类中的友元函数
- 类模板中使用友元函数
- 模板类中使用友元函数
- C++中模板类使用友元模板函数
- C++中模板类使用友元模板函数
- C++中模板类使用友元模板函数
- -C++中模板类使用友元模板函数
- 模板类中使用友元模板函数
- C++中模板类使用友元模板函数
- STL源码剖析 - 模板类中的友元函数
- [solved] g++ 模板类中的友元函数 链接出错
- 类模板中的友元
- 模板类的友元模板函数
- 模板类的 友元模板函数
- 类模板遇到友元函数模板
- 项目5-模板类中使用友元函数
- 九度OJ 1009 二叉搜索树
- MFC线程的全面总结
- PHP的socket详解
- windows文件操作函数
- 8 固若金汤:网站的安全架构
- 模板类中的友元函数使用注意
- Leetcode 284. Peeking Iterator
- Ubuntu下Hive配置(MySQL数据库的安装方式)
- Leetcode - Add Two Numbers
- JAVA JDK下载安装及配置环境变量
- LeetCode-9-Palindrome Number
- PHP的PDO
- Hibernate annotation
- eclipse快捷键