1. 程式人生 > >c/c++ 模板與STL小例子系列<二> 模板類與友元函數

c/c++ 模板與STL小例子系列<二> 模板類與友元函數

vat stream col ons cout include ios ring 沒有

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;
}

c/c++ 模板與STL小例子系列<二> 模板類與友元函數