C++之關於static關鍵字的充電---補充(7)《Effective C++》__C++

來源:互聯網
上載者:User

終於有時間啦,可以將以前挖的坑填啦。
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成員變數進行修改,不能調用普通成員變數。

加油哈,各位小夥伴們,越過雷區,就是通天大道,敢越雷池半步一步才只是一個開端,不怕荊棘,勇於鑽研,每一天都是一段最棒的旅程,加油啦。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.