码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 模板类友元之输出流操作符重载

时间:2016-07-12 19:38:04      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

几个关键点:

  需要前置声明!--奇怪的是别人告诉我也可以不需要,但我这里不行!

  友元函数的函数名后面的<>,必须要有。

 

#include <stdio.h>
#include <iostream>
using namespace std;

//前置声明,你妹啊
template<class T> class A;
template<class T> ostream &operator<< (ostream &out, const A<T> &_a);
template<class T1, class T2> class B;
template<class T1, class T2> ostream &operator<< (ostream &out, const B<T1, T2> &_b);

template<class T> class A
{
public:
    A(){}
    A(T _a, T _b):a(_a),b(_b){}
    ~A(){}
private:
    T a;
    T b;

    friend ostream &operator<< <> (ostream &out, const A<T> &a);
};

template<class T> ostream &operator<< (ostream &out, const A<T> &_a){
    out<<_a.a<<"--"<<_a.b;
    return out;
}

template<class T1, class T2> class B: public A<T1>
{
public:
    B(){}
    B(T1 _a, T1 _b, T2 _c):A<T1>(_a,_b),c(_c){} //A<T1>
    ~B(){}
private:    
    T2 c;

    friend ostream &operator<< <>(ostream &out, const B<T1, T2> &_b);
};
template<class T1, class T2> ostream &operator<< (ostream &out, const B<T1, T2> &_b){
    // out<<(A<T1>)_b;
    // out<<"--"<<_b.c;

    out<<(A<T1>)_b<<"--"<<_b.c;
    return out;
}

int main(int argc, char const *argv[])
{
    A<int> x(1, 3);
    B<char, int> y(a, b, 5);

    cout<< x <<endl;
    cout<< y <<endl;

    return 0;
}

 

C++ 模板类友元之输出流操作符重载

标签:

原文地址:http://www.cnblogs.com/larryzeal/p/5664418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!