1. 程式人生 > 實用技巧 >C++基礎-靜態函式和靜態變數(static)

C++基礎-靜態函式和靜態變數(static)

呼叫類裡面的函式,需要對這個類進行例項化,但是有時候想要直接呼叫基類裡面的資料,那麼這個時候就可以使用static對類的函式和變數進行宣告

使用時,不需要進行類的宣告

靜態函式只能呼叫靜態變數

#include <iostream>

using namespace std;

class Pet{
public:
    Pet(string theName);
    ~Pet();
    static int getCount();
protected:
    string name;
private:
    static int Count; //Count是私有屬性,只能在類的內部被呼叫 
}; Pet::Pet(string theName) { name = theName; cout << "出生了" << name << endl; Count ++; } Pet::~Pet() { cout << "掛掉了" << name << endl; Count --; } int Pet::getCount() { return Count; } class Cat : public Pet{ public: Cat(string theName); };
class Dog : public Pet{ public: Dog(string theName); }; Cat::Cat(string theName) : Pet(theName){ } Dog::Dog(string theName) : Pet(theName){ } int Pet::Count = 0; //進行類的外部宣告賦值 int main() { Cat cat("Tom"); Dog dog("Jerry"); cout << "已經誕生了" << Pet::getCount() << endl; { Cat cat_1(
"Tom_1"); Dog dog_1("Jerry_1"); cout << "已經誕生了" << Pet::getCount() << endl; //因為對getCounter進行了static,因此不需要例項化 } cout << "當前的數量是" << Pet::getCount() << endl; return 0; }