是否可以访问并使用类中的静态成员而无需先创建该类的实例?即将该类视为全局变量的某种倾销

詹姆斯

有帮助吗?

解决方案

您还可以通过空指针调用静态方法。下面的代码可以使用,但请不要使用它:)

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;
}

其他提示

是的,正是 static 对于班级成员意味着什么:

struct Foo {
    static int x;
};

int Foo::x;

int main() {
    Foo::x = 123;
}

另一方面,这就是命名空间的用途:

namespace toolbox
{
  void fun1();
  void fun2();
}

静态函数类的唯一用途是策略类。

简而言之,是的。

总之,可以在任何地方调用静态成员,只需将类名称视为命名空间。

class Something
{
   static int a;
};

// Somewhere in the code
cout << Something::a;

是:

class mytoolbox
{
public:
  static void fun1()
  {
    //
  }

  static void fun2()
  {
    //
  }
  static int number = 0;
};
...
int main()
{
  mytoolbox::fun1();
  mytoolbox::number = 3;
  ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top