終於有時間啦,可以將以前挖的坑填啦。
C++中的static與C語言有什麼不同呢。我們指導C++語言添加了OOP思想,相對於C語言中的static有了新的引用情境,下面我們就來分析一下C++中C語言部分的static屬性和C++ OOP部分的static屬性。 C語言部分static:
1)static局部變數
static局部變數在函數中調用的時候會最終返回的最新的static成員值,這個特性我們姑且稱之為“幻影”,看起來應該是以前的值,但是函數執行之後,static成員變數值總是會被更新為最新的值。
#include <iostream>#include <string>using namespace std;int& hel(int t){ static int i = t + 1; return i;}int main(){ int i = 10, j = 100; cout << hel(i) << " " << hel(j) << endl; if (hel(i) == hel(j)){ cout << "true" << endl; } else{ cout << "false" << endl; } return 0;}
運行結果為:
2)static全域變數
可以發現,當調用static全域變數的時候,會有相應的邏輯和儲存,因此,不會出現像static局部變數那樣總是返回當前值的行為。
#include <iostream>#include <string>using namespace std;static int i = 10;int hel(){ i++; return i;}int main(){ cout << i << endl; cout << hel() << endl; cout << hel() << endl; if (hel() == hel()){ cout << "true" << endl; } else{ cout << "false" << endl; } return 0;}
運行結果為:
3)static函數
static函數和static成員變數一樣,具有兩個屬性: 不能被其他檔案所引用; 其他檔案中可以定義同名的函數;
test1.cpp
#include <iostream>using namespace std;static void hello(){ cout << "hello" << endl;}
test.cpp
#include <iostream>#include <string>using namespace std;extern void hello();int main(){ hello(); return 0;}
我們可以發現報錯:
error LNK2019: 無法解析的外部符號 “void __cdecl hello(void)” (?hello@@YAXXZ),該符號在函數 _main 中被引用
如果我們改為如下代碼呢。
test1.cpp
#include <iostream>using namespace std;static void hello(){ cout << "hello" << endl;}
test.cpp
#include <iostream>#include <string>using namespace std;extern void hello();(static/non-static) void hello(){ cout << "hahaha" << endl;}int main(){ hello(); return 0;}
運行結果為:
C++ OOP中的特性呢。
1)static成員變數
static成員變數屬於整個類,值也有類在類外進行初始化設計;可以被static成員函數或者普通成員函數調用;
2)static成員函數
static成員函數只能對static成員變數進行修改,不能調用普通成員變數。
加油哈,各位小夥伴們,越過雷區,就是通天大道,敢越雷池半步一步才只是一個開端,不怕荊棘,勇於鑽研,每一天都是一段最棒的旅程,加油啦。。。