C++/Java__中類模板中的靜態成員變數和靜態成員函式
阿新 • • 發佈:2019-02-18
C++:
類模板例項化的每個模板類(每個模板類指的是對於宣告時候對模板指定的型別,如List<int>,List<double>中的int,double.)都有自己的類模板靜態資料成員,該模板類的所有物件,共享一個靜態資料成員。
Tips:
(重要)1.模板類的靜態資料成員應在檔案範圍內初始化。(包含模型)
(重要)2.每個模板類有自己的類模板的靜態資料成員和成員函式副本。
1.2詳見《C++Templates》示例程式碼:
#include <iostream> using namespace std; template < typename T > class Test { public: Test(T num){ k += num; } Test(){ k += 1; } static void incrementK() { k += 1; } static T k; }; template<typename T> T Test<T>::k = 0; int main() { //static Field Test<int> a; Test<double> b(4); cout << "Test<int>::k --> " << a.k << endl; cout << "Test<double>::k --> " << b.k << endl; Test<int> v; Test<double> m; cout << "Test<int>::k --> " << Test<int>::k << endl; cout << "Test<double>::k --> " << Test<double>::k << endl; //static Function cout << endl; Test<int>::incrementK(); cout << "After invoke Test<int>::incrementK() Test<int>::k --> " << Test<int>::k << endl; Test<double>::incrementK(); cout << "After invoke Test<double>::incrementK() Test<double>::k --> " << Test<double>::k << endl; return 0; }
測試輸出:
Java:
1、對於Java來說並不存在泛型類,List<String> l1和 List<String> l2會被當成一個類進行處理①測試程式如下,也沒有例項化的類生成額外的.class檔案。
2、不管為泛型的引數傳入何種實參,他們依舊被當做同一個類,因此在靜態方法,靜態初始化塊或者靜態變數的宣告和初始化中不允許使用型別形參。
①測試程式:
輸出:import java.util.ArrayList; import java.util.List; public class A3 { public static void main(String[] args) { // TODO Auto-generated method stub List<Integer> l1List = new ArrayList<>(); List<String> l2List = new ArrayList<>(); System.out.println(l1List.getClass() == l2List.getClass()); } }
試圖在泛型類中定義靜態變數,導致編譯錯誤:
public class R<T> {
static T info;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
錯誤: