在下面的示例中(取自 here ),我们有一个私有(private)静态变量 x,然后我们在类外部更改它的名称。让我困惑的是为什么允许在类之外更改私有(private)变量?那么将其声明为 private
的原因是什么。
// static_member_functions.cpp
#include <stdio.h>
class StaticTest
{
private:
static int x;
public:
static int count()
{
return x;
}
};
int StaticTest::x = 9;
int main()
{
printf_s("%d\n", StaticTest::count());
}
最佳答案
这不是“更改变量”,而是定义它。
每个 static
成员必须在类外部定义(static int x;
只是一个声明;如果删除 int StaticTest::x = 9;
将出现一个链接器错误,提示类似“对 StaticTest::x
的 undefined reference ”)。
尝试在main
中更改它,例如:
StaticTest::x = 13;
您将收到预期的错误(错误:'int StaticTest::x' is private
)。
关于c++ - 如果私有(private)变量是静态的,它们在类外部是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15920278/