C++快速入門---靜態屬性和靜態方法(15)
阿新 • • 發佈:2018-11-04
C++快速入門---靜態屬性和靜態方法(15)
靜態屬性和靜態方法
把一個或多個成員宣告為屬於某個類,而不是僅屬於該類的物件。
好處1:程式設計師可以在沒有建立任何物件的情況下呼叫有關的方法。
好處2:能夠讓有關的資料仍在該類的所有物件間共享。
程式碼如下:
#include <iostream> #include <string> class Pet { public: Pet(std::string theName); ~Pet(); static int getCount(); protected: std::string name; private: static int count; }; class Dog : public Pet { public: Dog(std::string theName); }; class Cat : public Pet { public: Cat(std::string theName); }; int Pet::count = 0; //注意這一句,他起碼做了兩件事 Pet::Pet(std::string theName) { name = theName; count++; std::cout << "一隻寵物出生了,名字叫做:" << name <<"\n"; } Pet::~Pet() { count--; std::cout << name << "掛掉了\n"; } int Pet::getCount() { return count; } Dog::Dog(std::string theName) : Pet(theName) { } Cat::Cat(std::string theName) : Pet(theName) { } int main() { Dog dog("Tom"); Cat cat("Jerry"); std::cout << "\n已經誕生了" << Pet::getCount() << "只寵物!\n\n"; { Dog dog_2("Tom_2"); Cat cat_2("Jerry_2"); std::cout << "\n現在呢,已經誕生了" << Pet::getCount() << "只寵物!\n\n"; } std::cout << "\n現在還剩下" << Pet::getCount() << "只寵物!\n\n"; return 0; }
this指標
this指標是類的一個自動生成、自動隱藏的私有成員,它存在於類的非靜態成員函式中,指向被呼叫函式所在的物件的地址。
當一個物件被建立時,該物件的this指標就自動指向物件資料的首地址。
#include <iostream> class Point { private: int x, y; public: Point(int a, int b) { x = a; y = b; } void MovePoint(int a, int b) { x = a; y = b; } void print() { std::cout << "x=" << x << "y=" << y << endl; } }; int main() { Point point1(10, 10); point1.MovePoint(2, 2); point1.print(); } //當物件point1呼叫MovePoint(2, 2)時,即將point1物件的地址傳遞給了this指標 //MovePoint函式的原型事實上應該是 void MovePoint(Point *this, int a, int b); //第一個引數是指向該類物件的一個指標,我們在定義成員函式時沒看見是因為這個引數在類中是隱含的。 //這樣point1的地址傳遞給了this,所以在MovePoint函式中便可以顯示的寫成:void MovePoint(int a, int b) //{this->x = a, this->y = b;} //即可以知道,point1呼叫該函式後,也就是point1的資料成員被呼叫並更新了值