C++之类的静态成员变量和静态成员函数
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                C++之类的静态成员变量和静态成员函数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                static靜態(tài)成員函數(shù)
在類中。static 除了聲明靜態(tài)成員變量,還能夠聲明靜態(tài)成員函數(shù)。普通成員函數(shù)能夠訪問全部成員變量。而靜態(tài)成員函數(shù)僅僅能訪問靜態(tài)成員變量。
我們知道。當調(diào)用一個對象的成員函數(shù)(非靜態(tài)成員函數(shù))時,系統(tǒng)會把當前對象的起始地址賦給 this 指針。而靜態(tài)成員函數(shù)并不屬于某一對象。它與不論什么對象都無關(guān),因此靜態(tài)成員函數(shù)沒有 this 指針。既然它沒有指向某一對象,就無法對該對象中的非靜態(tài)成員進行訪問。
能夠說。靜態(tài)成員函數(shù)與非靜態(tài)成員函數(shù)的根本差別是:非靜態(tài)成員函數(shù)有 this 指針。而靜態(tài)成員函數(shù)沒有 this 指針。由此決定了靜態(tài)成員函數(shù)不能訪問本類中的非靜態(tài)成員。
靜態(tài)成員函數(shù)能夠直接引用本類中的靜態(tài)數(shù)據(jù)成員,由于靜態(tài)成員相同是屬于類的,能夠直接引用。在C++程序中,靜態(tài)成員函數(shù)主要用來訪問靜態(tài)數(shù)據(jù)成員。而不訪問非靜態(tài)成員。
假設(shè)要在類外調(diào)用 public 屬性的靜態(tài)成員函數(shù)。要用類名和域解析符“::”。
如:
下面是一個完整演示樣例。 <pre name="code" class="cpp"> #include<iostream> #include<string> using namespace std;class Student{ private:string name;int age;float score;static int number; //定義靜態(tài)成員變量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(); }; /*注意。假設(shè)構(gòu)造函數(shù)的形參和 類的成員變量名字一樣。必須採用 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; } //靜態(tài)變量必須初始化。才干夠使用 int Student::number = 0; float Student::total = 0;int main(int argc,char*argv[]) {//即使沒有創(chuàng)建對象也能夠訪問靜態(tài)成員方法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 << "平均成績?yōu)?#34; << Student::getAverage() <<endl;system("pause");return 0; }
轉(zhuǎn)載于:https://www.cnblogs.com/liguangsunls/p/7281411.html
總結(jié)
以上是生活随笔為你收集整理的C++之类的静态成员变量和静态成员函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Window winload.efi 文
- 下一篇: 伽罗华域(有限域)及其运算规则(包含大量
