歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++類模板中的友元聲明及模板構造函數

C++類模板中的友元聲明及模板構造函數

日期:2017/3/1 9:11:19   编辑:Linux編程

類模板的友元聲明:

當授予給定模板的所有實例的訪問權的時候,在作用域中不需要存在該類模板或函數模板的聲明。想要限制對特定實例化的友元關系時,必須在可以用於友元聲明之前聲明類或函數。

template <class T>
class test
{
template <class U> friend ostream& operator<< (ostream &os, const test<U> &obj); //友元的所有實例均具有訪問權
...
};

class test;
template <class Type> ostream& operator<< (ostream &os, const test<Type> &obj);
template <class T>
class test
{
friend ostream& operator<< <T> (ostream &os, const test<T> &obj);//友元為的T類型實例才有訪問權
...
};

模板構造函數:

  在一個模板類中,構造函數和模板構造函數同時存在時,優先調用構造函數。只有當確切符合模板構造函數的接口時,才調用模板構造函數。編譯器永遠不會把模板構造函數視為構造函數,即使客戶沒有自己定義拷貝構造函數,編譯器也會生成一個默認的拷貝構造函數。

template <class T>
class test
{
public:
test() { cout << "in my test construct" << endl;}
test(const test &) { cout << "in my test copy" << endl;}
template <class V>
test(const test<V> &) { cout << "in my template copy" << endl;}
};


int main()
{
test<int> t1;
test<int> t2(t1);
test<double> t3(t1);
return 0;
}

此處的 template <class V> test(const test<V> &) 函數應該叫做類型轉換構造函數,它可以把一個test<T>的類型轉換成test<V>,也就是模版參數不同的模版類。這個應用就是比如說我有一個int類型的數組,要用來傳遞給一個double類型數組的參數,這個構造函數就可以完成這個轉換。

程序的輸出結構為:

in my test construct

in my test copy

in my template copy

在stl的pair和auto_ptr類中有應用

Copyright © Linux教程網 All Rights Reserved