質問
最初にそのクラスのインスタンスを作成せずに、クラス内の静的メンバーにアクセスして使用することは可能ですか?つまり、クラスをグローバルなある種のゴミ捨て場として扱います
ジェームズ
解決
また、nullポインターを介して静的メソッドを呼び出すこともできます。以下のコードは機能しますが、使用しないでください:)
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;
...
}
所属していません StackOverflow