niedziela, 30 kwietnia 2017

[C++]Static modifier

Local variables

Variables with static modifier are located in the same memory that global variables. Local static variables are not deleated. They remember their last values. Local static variables are initialized with 0 value.

#include <iostream>

int counter()
{
    static int a;
    a++;
    return a;
}

int main()
{
    std::cout<<counter()<<"\n"; // 1
    std::cout<<counter()<<"\n"; // 2
}

Static data members

Static data members of a class are created similarly like static local variables. Static data member is created earlier than first instance of this class. It doesn't matter from which object we can try to get acces to static data member, there is only one variable. Value is the same for all objects.

Also we can acces to static data member without any object. Static data member has to initialise like global variable.

#include <iostream>

class Foo
{
public:
    Foo ()
    {
        ++numberOfInstances;
    }
    static int numberOfInstances;
};

int Foo::numberOfInstances = 0;

int main()
{
    std::cout<<Foo::numberOfInstances<<"\n";// acces to member without object
    Foo a;
    std::cout<<a.numberOfInstances<<"\n";// 1
    Foo b, c;
    std::cout<<b.numberOfInstances<<"\n";// 3
}

Member functions

Static member functions are not associated with any objects. Static member functions have acces only to static data members. They cannot be: virtual, const and volatile.

#include <iostream>

class Foo
{
public:
    Foo ()
    {
        ++numberOfInstances;
    }

    static int getNumberOfInstances()
    {
        z = 4;// error, 'z' is not static!
        this-<numberOfInstances = 0;//error, cannot use 'this' in static functions
        return numberOfInstances;
    }

private:
    int z =3;
    static int numberOfInstances;
};

int Foo::numberOfInstances = 0;

int main()
{
    std::cout<<Foo::getNumberOfInstances()<<"\n";// acces to static function without object
    Foo a;
    std::cout<<a.getNumberOfInstances()<<"\n";// acces to static function with object
}

Brak komentarzy:

Prześlij komentarz