靜態成員是可以獨立訪問的,也就是說,無須創建任何對象實例就可以訪問,而靜態成員函數可不建立對象就可以被使用。
或者說靜態函數與一般函數沒有太大的區別,只是訪問有限制,靜態變量跟一般的全局變量的區別就是訪問有限制。
static變量
static變量不像普通的變量,static變量獨立於一切類對象處在。static修飾的變量先於對象存在,所以static修飾的變量要在類外初始化。因為static是所有對象共享的東西嘛,必須要比對象先存在的。
class test
{
private:
public:
static int i;
};
int test::i = 100;//此句包含了聲明和賦值,初始化不受private和protected訪問限制,但是若是priivate,下面main函數就無法訪問
int main()
{
cout << test::i << endl;
return 0;
}
好處:用static修飾的成員變量在對象中是不占內存的,因為他不是跟對象一起在堆或者棧中生成,用static修飾的變量在靜態存儲區生成的,所以用static修飾一方面的好處是可以節省對象的內存空間。所以一般類const變量一般改為static const變量,可以節省一些空間。
C++ 類 的static 非const變量如何避免多重定義
header.h
#ifndef HEADER_H_
#define HEADER_H_
class test{
public:
static bool b;
};
#endif
cpp1.cpp
#include "header.h"
void f1()
{
if(test::b)
std::cout << "cpp1" << std::endl;
}
cpp2.cpp
#include "header.h"
void f2()
{
if(test::b)
std::cout << "cpp2" << std::endl;
}
main.cpp
void f1();
void f2();
int main()
{
f1();
f2();
return 0;
}
我的解決方案
header.h
#ifndef HEADER_H_
#define HEADER_H_
class test{
public:
static bool b;
};
#endif
header.cpp
#include "header.h"
bool test::b = false;
cpp1.cpp
#include "header.h"
void f1()
{
if(test::b)
std::cout << "cpp1" << std::endl;
}
cpp2.cpp
#include "header.h"
void f2()
{
if(test::b)
std::cout << "cpp2" << std::endl;
}
main.cpp
void f1();
void f2();
int main()
{
f1();
f2();
return 0;
}
注:如果既是const又是static,直接在header.h里面賦予初始值即可,無需header.cpp
static成員函數
static函數也是類函數,所以在寫定義時也要寫明屬於哪個類。與不同類函數不同的是,它沒有傳入this指針,正因為沒有this指針,所以static類成員函數不能訪問非static的類成員,只能訪問 static修飾的類成員。
靜態成員函數不可以同時聲明為 virtual、const、volatile函數。
class test
{
public:
static int i;//此處只是聲明變量
static void f();//聲明
};
int test::i;//此處是定義,少了此處會鏈接錯誤
void test::f()//定義
{
i = 1000;
cout << i << endl;
}
int main()
{
//test a;
test::f();
return 0;
}