简体   繁体   English

在C ++中达到静态变量

[英]Reaching static variables in C++

If I define a static variable in classA: 如果我在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. 我可以直接使用m_val以便在ClassA(或任何其他类)中访问它,还是应该像classA :: m_val一样使用它。

Inside of ClassA , just write m_val . ClassA内部,只需编写m_val Outside of ClassA , ClassA::m_val . ClassA之外, ClassA::m_val

However, m_val is not const in your example, so it (typically) should be private anyway. 但是, m_val在您的示例中不是const ,因此无论如何它(通常)应该是私有的。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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