3

1.静态结构除了联动还有什么用?

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

2.像这样使用静态有什么用?当我创建它并尝试使用静态成员(通过结构对象)时,它显示“未定义的对 `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. 这是一个静态字段。如果您在 struct 中声明某个字段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 回答