[英]C++ static members in class
Is it possible to access to access and use static members within a class without first creating a instance of that class? 是否可以在不首先创建该类的实例的情况下访问和使用类中的静态成员? Ie treat the the class as some sort of dumping ground for globals
即将该类视为全局变量的某种倾销
James 詹姆士
Yes, it's precisely what static
means for class members: 是的,这正是集体成员的
static
意义:
struct Foo {
static int x;
};
int Foo::x;
int main() {
Foo::x = 123;
}
On the other hand, that's what namespace are for: 另一方面,这就是命名空间的用途:
namespace toolbox
{
void fun1();
void fun2();
}
The only use of classes of static functions is for policy classes. 静态函数类的唯一用途是用于策略类。
In short, yes. 简而言之,是的。
In long, a static member can be called anywhere, you simply treat the class name as a namespace. 总之,可以在任何地方调用静态成员,只需将类名称视为命名空间即可。
class Something
{
static int a;
};
// Somewhere in the code
cout << Something::a;
Yes: 是:
class mytoolbox
{
public:
static void fun1()
{
//
}
static void fun2()
{
//
}
static int number = 0;
};
...
int main()
{
mytoolbox::fun1();
mytoolbox::number = 3;
...
}
You can also call a static method through a null pointer. 您还可以通过空指针调用静态方法。 The code below will work but please don't use it:)
下面的代码可以使用,但请不要使用它:)
struct Foo
{
static int boo() { return 2; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Foo* pFoo = NULL;
int b = pFoo->boo(); // b will now have the value 2
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.