Metodi Statici C++
Dichiarazione e uso dei metodi statici all'interno della classe
Il metodo statico in C++ appartiene alla classe anziché a un'istanza specifica della classe.
Ciò significa che può essere chiamato senza dover creare un'istanza dell'oggetto.
I metodi statici non possono accedere a membri non statici della classe e possono essere chiamati utilizzando il nome della classe anziché un'istanza dell'oggetto.
#include <iostream>
#include <string>
class MyClass {
private:
static int myAttr; // Private static attribute
public:
// Static method to set the value of myAttr
static void SetMyAttr(int newValue) {
myAttr = newValue;
}
// Static method to get the value of myAttr
static int GetMyAttr() {
return myAttr;
}
};
// Initialization of the static attribute myAttr
int MyClass::myAttr = 0;
int main() {
// Creating an object of the class MyClass
MyClass myObject;
// Using the static method to set the value of myAttr
MyClass::SetMyAttr(42);
// Using the static method to get the value of myAttr
std::cout << "Value of myAttr: " << MyClass::GetMyAttr() << std::endl;
return 0;
}