模板类中的友元函数使用注意

时间:2023-01-22 19:11:45
<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;
}
}
运行结果:

模板类中的友元函数使用注意

模板类中的友元函数使用注意