88.類的靜態成員,以及繼承多線程類的實現
阿新 • • 發佈:2018-03-18
... clas 繼承 子類 pub iostream thread 靜態 通信
1 #include <iostream> 2 #include <thread> 3 using namespace std; 4 5 class myclass 6 { 7 public: 8 //static只會初始化一次 9 static int num; 10 myclass() 11 { 12 num += 1; 13 } 14 ~myclass() 15 { 16 num -= 1; 17 } 18 }; 19 21 //靜態成員不屬於任何一個對象,任何對象都可以訪問 22 //用於同類對象通信23 int myclass::num = 3; 24 25 class mythread : public thread 26 { 27 public: 28 static int count; 29 30 public: 31 //重載兩個構造函數 32 mythread() : thread()//子類調用父類構造函數 33 { 34 35 } 36 template<typename T,typename...Args> 37 mythread(T &&func, Args &&...args) : thread(forward<T>(func), forward<Args>(args)...)38 { 39 40 } 41 }; 42 43 int mythread::count = 0; 44 45 void go() 46 { 47 while(1) 48 { 49 mythread::count += 1; 50 cout << this_thread::get_id() << " " << mythread::count << endl; 51 this_thread::sleep_for(chrono::seconds(3)); 52 }53 54 } 55 56 void main() 57 { 58 //myclass my1, my2, my3; 59 //cout << my1.num << endl; 60 //cout << my2.num << endl; 61 //cout << my3.num << endl; 62 63 mythread my1(go); 64 mythread my2(go); 65 mythread my3(go); 66 cin.get(); 67 }
88.類的靜態成員,以及繼承多線程類的實現