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

<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;
    }
}
运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值