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;
}