2

是否可以在不首先创建该类的实例的情况下访问和使用类中的静态成员?即将班级视为某种全球性的垃圾场

詹姆士

4

5 回答 5

6

是的,这正是static对班级成员的意义:

struct Foo {
    static int x;
};

int Foo::x;

int main() {
    Foo::x = 123;
}
于 2009-10-28T21:45:40.743 回答
3

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

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

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

于 2009-10-29T08:04:51.420 回答
2

简而言之,是的。

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

class Something
{
   static int a;
};

// Somewhere in the code
cout << Something::a;
于 2009-10-28T21:46:14.910 回答
0

是的:

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

  static void fun2()
  {
    //
  }
  static int number = 0;
};
...
int main()
{
  mytoolbox::fun1();
  mytoolbox::number = 3;
  ...
}
于 2009-10-28T21:45:28.680 回答
-1

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

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;
}
于 2009-10-28T22:43:38.700 回答