Static değişkenler ve fonksiyonlar nesnelerden bağımsız olarak sınıfa aittir. Bunlara erişmek ve kullanmak için herhangi bir nesneye ihtiyacımız yoktur. Nesnelerden bağımsız olduğu için tüm nesneler aynı değişkene/fonksiyona erişebilir.
// main.cpp
#include <iostream>
using namespace std;
class Player {
string name;
int health;
int ID;
static int globalID;
public:
Player(string name, int health) : name{ name }, health{ health } {
ID = globalID++;
}
int getID() { return ID; }
static int getGlobalID() { return globalID; }
};
int Player::globalID = 0;
int main() {
cout << "Player::globalID : " << Player::getGlobalID() << endl;
// Player::globalID : 0
Player p1("ahmet", 100);
Player p2("mehmet", 100);
Player p3("selim", 100);
cout << "p2 ID: " << p2.getID() << endl; // p2 ID : 1
cout << "p3 ID: " << p3.getID() << endl; // p3 ID : 2
cout << "p1 ID: " << p1.getID() << endl; // p1 ID : 0
cout << "Player::globalID : " << Player::getGlobalID() << endl;
// Player::globalID : 3
}
Leave a Reply