原文鏈接:https://blog.csdn.net/chengqiuming/article/details/89738995
參考鏈接:
https://blog.csdn.net/weixin_41783335/article/details/92784826
https://blog.csdn.net/qq_38124695/article/details/78188411
一 點睛
與靜態數據成員不同,靜態成員函數的作用不是為了對象之間的溝通,而是為了能處理靜態數據成員。
靜態成員函數沒有this指針。既然它沒有指向某一對象,也就無法對一個對象中的非靜態成員進行默認訪問(即在引用數據時不指定對象名)。
靜態成員函數和非靜態成員函數的根本區別:非靜態成員函數有this指針,而靜態成員函數沒有this指針。由此決定了靜態成員函數不能訪問本類中的非靜態成員。
靜態成員函數可以直接引用本類中的靜態數據成員,靜態成員函數主要用來訪問靜態數據成員,而不訪問非靜態成員。
假如在一個靜態成員函數中有如下語句:
cout<<height<<endl; //若height已聲明為static,則引用本類中的靜態成員,合法 cout<<width<<endl; //若width是非靜態成員,不合法
但並不是說絕對不能引用本類中的非靜態成員,只是不能進行默認訪問,因為無法知道去找哪個對象。如果一定要引用本類中的非靜態成員,應該加對象名和成員運算符".",如:
cout<<a.width<<endl; //引用本類對象a的非靜態成員
最好養成這樣的習慣:只用靜態成員函數引用靜態數據成員,而不引用非靜態數據成員。
二 實戰
1 代碼
#include<iostream> using namespace std; class CStudent{ public: CStudent (int n,int s):num(n),score(s){}//定義構造函數 void total(); static double average(); private: int num; int score; static int count; static int sum;//這兩個數據成員是所有對象共享的 }; int CStudent::count=0;//定義靜態數據成員 int CStudent::sum=0; void CStudent::total(){//定義非靜態成員函數 sum+=score; //非靜態數據成員函數中可使用靜態數據成員、非靜態數據成員 count++; } double CStudent::average(){//定義靜態成員函數 return sum*1.0/count;//可以直接引用靜態數據成員,不用加類名 } int main(){ CStudent stu1(1,100); stu1.total();//調用對象的非靜態成員函數 CStudent stu2(2,98); stu2.total(); CStudent stu3(3,99); stu3.total(); cout<< CStudent::average()<<endl;//調用類的靜態成員函數,輸出99 }
2 運行
[root@localhost charpter02]# g++ 0213.cpp -o 0213 [root@localhost charpter02]# ./0213 99
總結:




