C++ Primer 5th笔记(chap 16 模板和泛型编程)类模板和static
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(chap 16 模板和泛型编程)类模板和static
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 定義
與任何其他static數據成員相同,模板類的每個static數據成員必須有且僅有一個定義。類模板的每個實例都有一個獨有的static對象。
eg. Foo是一個類模板
- 有一個名為count的public static 成員函數
- 一個名為ctr的private static數據成員。
每個Foo的實例都有其自己的static成員實例。即,對任意給定類型x,都有一個Foo: :ctr和一個Foo: : count成員。所有Foo類型的對象共享相同的ctr對象和count函數。
template <typename T> class Foo {public:static std: :size_ t count () { return ctr; }//其他接口成員private :static std: :size t ctr;//其他實現成員 };//實例化static成員Foo<string>: :ctr和Foo<string>: :count Foo<string> fs;//所有三個對象共享相同的Foo<int>: :ctr和Foo<int>: :count成員 Foo<int> fi, fi2, fi3; Foo<int> fi;//實例化Foo<int>類和static數據成員ctr auto ct = Foo<int>: :count() ; // 實例化Foo<int>: : count ct = fi.count () ;//使用Foo<int>: :count ct = Foo: :count() ;//錯誤:使用哪個模板實例的count?1.1 變量初始化
template size t Foo: :ctr = 0; //定義并初始化ctr .
1.2 類似任何其他成員函數,一個static成員函數只有在使用時才會實例化。
總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 16 模板和泛型编程)类模板和static的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: C++ Primer 5th笔记(cha