当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c/c++ 模板与STL小例子系列<二> 模板类与友元函数

c/c++ 模板与STL小例子系列<二> 模板类与友元函数

2018年08月29日  | 移动技术网IT编程  | 我要评论

sacredseven,华硕贝壳机,自从你走后 胡东

c/c++ 模板与stl小例子系列<二> 模板类与友元函数

比如某个类是个模板类d,有个需求是需要重载d的operator<<函数,这时就需要用到友元。

实现这样的友元需要3个必要步骤

1,在模板类d的实现代码的上面声明友元函数

template<typename> class d;//因为友元函数的参数里使用了d,所以要先在这里声明一下
template<typename t>
ostream& operator<< (ostream&, const d<t> &);

2,在模板类d的实现代码里面声明它是我的友元

//注意operator<<后面有<t>                                                  
friend ostream& operator<< <t>(ostream& ,const d<t>&);

3,实现友元函数

template<typename t>
//注意operator<<后面没有<t> 
ostream& operator << (ostream& out,const d<t>& d){
  out << d.x;
  return out;
}

例子代码:

#include <iostream>
using namespace std;

template<typename t>
class test{
public:
  test(t t) : data(t){}
  virtual void show() = 0;
private:
  t data;
};

template<typename> class d;
template<typename t>
ostream& operator<< (ostream&, const d<t> &);

template<typename t>
class d : public test<t>{
  //注意有<t>                                                  
  friend ostream& operator<< <t>(ostream& ,const d<t>&);
public:

  //注意不是test(t1)                                           
  d(t t1, t t2) : test<t>(t1), x(t2){}
  void show(){
    cout << x << ", " << x << endl;
  }
private:
  t x;
};

template<typename t>
ostream& operator << (ostream& out,const d<t>& d){
  out << d.x;
  return out;
}

int main(void){
  test<int> *p = new d<int>(10, 21);
  p->show();
  d<int> d(10,20);
  cout << d << endl;
  return 0;
}

模板类继承非模板类,非模板类继承模板类

下面的例子没有什么实际意义,只看语法。

#include <iostream>
using namespace std;

class foo{
public:
  foo(int a, int b, int c) : x(a), y(b), z(c){}
  void show(){
    cout << x << "," << y << "," << z << endl;
  }
private:
  int x, y, z;
};

template <typename t>
class goo : public foo{
public:
  goo(t t, int a, int b, int c):foo(a,b,c), data(t){}
  void show(){
    cout << data << endl;
    cout << "goo show" << endl;
  }
private:
  t data;
};

class hoo : public goo<int>{
public:
  hoo(int a1,int a2,int a3,int a4,int a5):
    goo(a1,a2,a3,a4),ho(a5){}
  void show(){
    cout << "hoo show" << endl;
  }
private:
  int ho;
};
int main(void){
  hoo hoo(1,2,3,4,5);
  hoo.show();
  goo<string> goo("abc",1,2,3);
  goo.show();
  return 0;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网