简体   繁体   中英

Reaching static variables in C++

If I define a static variable in classA:

static int m_val;

and initialize like

int classA::m_val = 0;

Can I use directly m_val as it is in order to access it in ClassA (or any other class) or should I use it like classA::m_val.

Inside of ClassA , just write m_val . Outside of ClassA , ClassA::m_val .

However, m_val is not const in your example, so it (typically) should be private anyway. In that case, you'd not access it directly from other classes but provide a member function to retrieve a copy:

class ClassA
{
private:
    static int m_val;
// ...
public:
    static int GetVal();
};

Implementation:

int ClassA::m_val = 0;

int ClassA::GetVal()
{
    return m_val;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM