標籤:cout const use pos 成員 pause 2.4 src []
static靜態成員函數在類中。static 除了聲明靜態成員變數,還能夠聲明靜態成員函數。
普通成員函數能夠訪問全部成員變數。而靜態成員函數僅僅能訪問靜態成員變數。
我們知道。當調用一個對象的成員函數(非靜態成員函數)時,系統會把當前對象的起始地址賦給 this 指標。而靜態成員函數並不屬於某一對象。它與不論什麼對象都無關,因此靜態成員函數沒有 this 指標。既然它沒有指向某一對象,就無法對該對象中的非靜態成員進行訪問。
能夠說。靜態成員函數與非靜態成員函數的根本差別是:非靜態成員函數有 this 指標。而靜態成員函數沒有 this 指標。由此決定了靜態成員函數不能訪問本類中的非靜態成員。
靜態成員函數能夠直接引用本類中的待用資料成員,由於靜態成員相同是屬於類的,能夠直接引用。在C++程式中,靜態成員函數主要用來訪問待用資料成員。而不訪問非靜態成員。
假設要在類外調用 public 屬性的靜態成員函數。要用類名和域解析符“::”。
如:
下面是一個完整示範範例。
<pre name="code" class="cpp">#include<iostream>#include<string>using namespace std;class Student{private:string name;int age;float score;static int number; //定義靜態成員變數static float total;public:Student(string name,int age,float score);Student(const Student & s);~Student();void setName(string n);string getName();void setAge(int a);int getAge();void setScore(float s);float getScore();void say();static float getAverage();};/*注意。假設建構函式的形參和 類的成員變數名字一樣。必須採用 this -> name = name ,而不能夠 寫成 name = name*/Student::Student(string name,int age,float score){this->name = name;this ->age = age;this ->score = score;number++;total += score;}Student::Student(const Student & s){this ->name = s.name;this ->age = s.age;this ->score = s.score;}Student::~Student(){}string Student::getName(){return this->name;}int Student::getAge(){return this->age;}float Student::getScore(){return this ->score;}void Student::setName(string n){this ->name = n;}void Student::setAge(int a){this ->age =a ;}void Student::setScore(float s){this->score =s;}void Student::say(){cout << this->name <<" : " << this->age <<" : " << this ->score << " : " << Student::number <<endl;}float Student::getAverage(){if(number == 0){return 0;}elsereturn total/number;}//靜態變數必須初始化。才幹夠使用int Student::number = 0;float Student::total = 0;int main(int argc,char*argv[]){//即使沒有建立對象也能夠訪問靜態成員方法cout << "沒有學生的時候的平均成績"<< Student::getAverage() <<endl;Student s1("lixiaolong",32,100.0);Student s2("chenglong",32,95.0);Student s3("shixiaolong",32,87.0);s1.say();s2.say();s3.say();cout << "平均成績為" << Student::getAverage() <<endl;system("pause");return 0;}
C++之類的靜態成員變數和靜態成員函數