3

1.リンケージ以外の静的構造の用途は何ですか?

static struct test //THIS ONE
{
  int a;
};

2.このような static を使用する用途は何ですか? これを作成し、(構造体オブジェクトを介して) 静的メンバーを使用しようとすると、「`test::a' への未定義の参照」が表示されます。

struct test
{
  static int a; //THIS ONE
};

3. 静的構造オブジェクトの作成の用途は何ですか?

struct test{
  int a;
};

int main()
{
  static test inst; //THIS ONE
  return 0;
}
4

1 に答える 1

5
  1. これはリンケージに固有のものです-test構造に内部リンケージを持たせます(現在のファイルでのみ表示されます)。編集:これは、関数と変数の宣言にのみ有効です。型定義には有効ではありません。

    //A.cpp
    static int localVar = 0;
    
    void foo(){ localVar = 1; /* Ok, it's in the same file */ }
    
    //B.cpp
    extern int localVar;
    void bar(){ 
    /* 
       Undefined reference - linker can't see
       localVar defined as static in other file. 
    */
       localVar = 2; 
    }
    
  2. これは静的フィールドです。構造体内でいくつかのフィールドを宣言するstaticと、その構造体のすべてのインスタンスの共有データ メンバーになります。

     struct test
     {
         static int a;
     };
    
    
     // Now, all your test::a variables will point to the same memory location.
     // Because of that, we need to define it somewhere in order to reserve that 
     // memory space!
     int test::a;
    
     int foo()
     {
         test t1, t2;
         t1.a = 5;
         test::a = 6;
         std::cout << t2.a << std::endl; // It will print 6.
     }
    
  3. これは静的ローカル変数です。これはコールスタックではなくグローバル領域に保存されるため、同じ関数へのすべての呼び出しは同じinst変数を共有します。

       void foo()
       {
            static int i = 0;
            i++;
            std::cout << i << std::endl;
       }
    
       int main()
       {
           foo();  // Prints 1
           foo();  // Prints 2
           foo();  // Prints 3
           return 0;
       }
    
于 2013-08-18T19:01:25.603 に答える