模板与友元

//  模板与友元
#include "stdafx.h"
#include<iostream>

using namespace std;

// 要进行前向声明
template<class T>   class Friendly;
// 要进行前向声明
template<class T>   void f(const Friendly<T>& );

template<class T>
class Friendly
{
    T t;

public:
    Friendly(const T& theT): t(theT) { }

    // 友元函数  用<>表示其函数为友元的模板函数,不是友元的普通函数
    friend void f<> (const Friendly<T>&);
    void g()   { f(*this); }
};

void h()
{
    f(Friendly<int>(1));
}


template<class T>
void f(const Friendly<T>& fo)
{
    std::cout<<fo.t<<std::endl;
}

int main()
{
    h();
    Friendly<int>(2).g();

    system("pause");
    return 0;
}

// 模板与友元2  提供一个简单的流来验证程序所做的工作
#include "stdafx.h"
#include<iostream>
using namespace std;

// Forward declarations   前向声明
template<class T> class Box;

template<class T>
Box<T> operator+(const Box<T>&, const Box<T>&);

template<class T>
ostream& operator<<(ostream&, const Box<T>&);

template<class T>
class Box
{
    T t;

public:
    Box(const T& theT): t(theT) { }

    // 重载运算符的模板函数
    friend Box operator+<>(const Box<T>&, const Box<T>&);
    friend ostream& operator<< <>(ostream&, const Box<T>&);
};

template<class T>
Box<T> operator+(const Box<T>& b1, const Box<T>& b2)
{
    return Box<T>(b1.t + b2.t);
}


template<class T>
ostream& operator<<(ostream& os, const Box<T>& b)
{
    return os<<'['<<b.t<<']'<<std::endl;
}

int main()
{
    Box<int> b1(1), b2(2);
    cout<<b1+b2;

    system("pause");
    return 0;
}

// 以上代码有个缺点  无法提供隐式转换, 使用内部类,非模板的方法
// 使程序更短小,更强健
#include "stdafx.h"
#include<iostream>
using namespace std;

// Forward declarations   前向声明
template<class T>
class Box
{
    T t;

public:
    Box(const T& theT): t(theT) { }

    // 重载运算符的模板函数
    friend Box operator+(const Box<T>& b1, const Box<T>& b2)
    {
        return Box<T>(b1.t + b2.t);
    }

    friend ostream& operator<<(ostream& os, const Box<T>& b)
    {
        return os<<'['<<b.t<<']'<<std::endl;
    }
};

int main()
{
    Box<int> b1(1), b2(2);
    cout<<b1+b2;
    cout<<b1+3;

    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值