26-類的靜態成員函數

26-類的靜態成員函數

類的成員函數

在C++中可以定義靜態成員函數:

  • 靜態成員函數是類中特殊的成員函數
  • 靜態成員函數屬於整個類所有
  • 可以通過類名直接訪問公有靜態成員函數
  • 可以通過對象名訪問公有靜態成員函數

靜態成員函數的定義

  • 直接通過static關鍵字修飾成員函數
class Test {
public:
	static void Func1() {}
	static int Func2();
};
int Test::Func2() {
	return 0;
}

【範例代碼】靜態成員函數的使用

#include <stdio.h>

class Demo {
private:
    int i;
public:
    int getI();
    static void StaticFunc(const char* s);
    static void StaticSetI(Demo& d, int v);
};

int Demo::getI() {
    return i;
}

void Demo::StaticFunc(const char* s) {
    printf("StaticFunc: %s\n", s);
}

void Demo::StaticSetI(Demo& d, int v) {
    d.i = v;
}

int main(int argc, const char* argv[]) {
    Demo::StaticFunc("main Begin...");

    Demo d;
    Demo::StaticSetI(d, 10);
    printf("d.i = %d\n", d.getI());
    Demo::StaticFunc("main End...");

    return 0;
}

靜態成員函數 VS 普通成員函數


發佈了52 篇原創文章 · 獲贊 4 · 訪問量 7505
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章