“静态”到底是什么?声明“全局”时的意思是C++ 中的变量?

发布于 2024-09-12 20:58:57 字数 214 浏览 6 评论 0原文

这是上一个范围的扩展我的问题

“静态”到底是什么,它是如何使用的,以及在处理 C++ 时使用“静态”的目的是什么?

谢谢。

This is an expansion of the scope of a previous question of mine.

What exactly is "static", how is it used, and what is the purpose of using "static" when dealing with C++?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

洒一地阳光 2024-09-19 20:58:57

这意味着该变量是翻译单元的本地变量(简单地说,是单个源文件),并且不能从外部访问。实际上,当前的 C++ 标准中不推荐使用 static 的这种方式 - 相反,您应该使用匿名命名空间:

static int x = 0;    

应该是:

namespace {
    int x = 0;    
}

It means that the variable is local to a translation unit (simply put, to a single source file), and cannot be accessed from outside it. This use of static is in fact deprecated in the current C++ Standard - instead you are supposed to use anonymous namespaces:

static int x = 0;    

should be:

namespace {
    int x = 0;    
}
差↓一点笑了 2024-09-19 20:58:57

关键字 static 在 C++ 中具有不同的含义,具体取决于上下文。

声明自由函数或全局变量时,这意味着该函数在该单个翻译单元之外不可用:

// test.cpp
static int a = 1;
static void foo() {}

如果编译该翻译单元的结果与包含符号 afoo 不会违反单一定义规则,因为在这个特定的翻译单元中 afoo私有 符号。这种用法已被未命名的命名空间所取代。

// test2.cpp
namespace {
   static int a = 1;
   static void foo() {}
}

在函数内声明局部变量时,这意味着变量的生命周期将从第一次调用函数延伸到程序结束,而不仅仅是在调用期间:

int foo() {
   static int counter = 0;
   return ++counter;
}
int main() {
  for ( int i = 0; i < 10; ++i ) { 
     std::cout << foo() << std::endl;
  }
}

在前面的代码中,counter 在第一次调用 foo 时初始化一次,但该变量的寿命将比函数长,并在不同的函数调用之间保留该值。前面的代码将打印“1 2 3 4... 10”。如果变量未声明为static,则输出将为“1 1 1... 1”。

在类范围内,static 意味着该成员是该类的成员,而不是特定实例的成员。这种用法等同于您的其他问题中的用法:该特定成员的使用不绑定到任何特定对象。

struct test {
   int x;
   static int y;
};
int test::y;       // need to define it in one translation unit
int main() {
   // test::x = 5; // !error cannot access a non-static member variable
                   // without an instance
   test::y = 5;    // ok
   test t, other;
   t.x = 10;       // ok
   t.y = 15;       // ok, the standard allows calling a static member through
                   // an instance, but this is the same as test::y
}

在本例中,成员 x 是非静态成员属性,因此该类的每​​个实例都有不同的 x。在示例程序中,txother.x 引用不同的整数。另一方面,ystatic,因此程序中只有一个 test::y 实例。即使标准允许调用 tyother.y 两者都使用引用相同的变量。成员方法也是如此。如果它们是静态的,则它们是类级方法,并且可以在没有实例的情况下调用,而如果它们是非静态的,则它们将应用于具体实例,并且 aba->必须使用 b 语法。

static 的这种使用类似于 Java 中相同关键字的使用,而该语言中不存在其他两个关键字。 Java 中关键字的一种用法在 C++ 中不存在,那就是使用静态类初始值设定项(由 static { ... } 包围的类级别代码块)。在 Java 中,该代码块将在类加载时执行,并且仅执行一次。 C++ 中静态成员变量的初始化必须在变量定义的初始值设定项中完成。

The keyword static has different meanings in C++, depending on the context.

When declaring a free function or a global variable it means that the function is not to be available outside of this single translation unit:

// test.cpp
static int a = 1;
static void foo() {}

If the result of compiling that translation unit is linked with a different translation unit containing symbols a and foo it will not break the One Definition Rule, as in this particular translation unit a and foo are private symbols. This use has been obsoleted by unnamed namespaces.

// test2.cpp
namespace {
   static int a = 1;
   static void foo() {}
}

When declaring a local variable within a function it means that the lifetime of the variable will extend from the first call to the function to the end of the program, and not only for the duration of the call:

int foo() {
   static int counter = 0;
   return ++counter;
}
int main() {
  for ( int i = 0; i < 10; ++i ) { 
     std::cout << foo() << std::endl;
  }
}

In the previous code, counter is initialized once when foo is called for the first time, but the variable will outlive the function and keep the value across different function calls. The previous code will print "1 2 3 4... 10". If the variable was not declared static then the output would be "1 1 1... 1".

Within a class scope, static means that the member is a member of the class, and not of a particular instance. This use is equivalent to the use in your other question: usage of that particular member is not bound to any specific object.

struct test {
   int x;
   static int y;
};
int test::y;       // need to define it in one translation unit
int main() {
   // test::x = 5; // !error cannot access a non-static member variable
                   // without an instance
   test::y = 5;    // ok
   test t, other;
   t.x = 10;       // ok
   t.y = 15;       // ok, the standard allows calling a static member through
                   // an instance, but this is the same as test::y
}

In this case, the member x is a non-static member attribute, and as such there is a different x for each instance of the class. In the sample program t.x and other.x refer to different integers. On the other hand y is static and thus there is a single instance of test::y in the program. Even if the standard allows to call t.y and other.y both uses refer to the same variable. The same goes with member methods. If they are static they are class-level methods and can be called without an instance, while if they are non-static they are applied to a concrete instance and the a.b or a->b syntax must be used.

This use of static is similar to the use of the same keyword in Java, while the other two are not present in that language. There is one use of the keyword in Java that is not present in C++, and that is the use of static class initializers (a block of code at class level surrounded by static { ... }). In Java that block of code will be executed when the class is loaded and only once. Initialization of static member variables in C++ must be done in the initializer of the variable definition.

一杯敬自由 2024-09-19 20:58:57

此处似乎对这些内容进行了很好的介绍。

但换句话来说,C 中有两种用途:

  1. 防止在定义全局变量的文件范围之外使用全局变量。
  2. 允许函数内的局部变量在函数的调用中持续存在,如下所示

    int getNextId()
    {
    静态 int id = 0;
    返回id++;
    }

,并添加了它自己的两个用途。

  1. 静态成员变量:在类的所有实例中“共享”的变量,并且也可以在不引用类实例的情况下进行访问。共享似乎是一个错误的词,但本质上我相信结果是对静态成员变量的任何引用都引用相同的内存位置。
  2. 静态方法:无需引用定义它的类的特定实例即可调用的方法。

This stuff seems to be fairly well covered here.

But to paraphrase, there are 2 uses in C

  1. Prevent the use of a global variable outside the scope of the file that defines it.
  2. Allow local variables within a function to persist accross invocations of the function, as in

    int getNextId()
    {
    static int id = 0;
    return id++;
    }

C++ inherits both of these, and adds two uses of its own.

  1. static member variables: Variables that are "shared" accross all instances of a class, and can also be accesses without reference to an instance of the class. Shared seems like the wrong word, but in essence I beleive that the result is that any reference to a static member variable references the same memory location.
  2. static methods: Methods that can be called without reference to a specific instance of the class that defines it.
飘落散花 2024-09-19 20:58:57

静态基本上意味着变量与程序的生命周期相关,而不是与任何给定的函数或类实例相关。你什么时候应该使用它?不。目的是什么?主要是调试数据。

一般来说,在 C++ 中,如果您发现自己使用静态数据,那么您就做错了。有时这是合适的,但这种情况非常罕见。

Static basically means that a variable is tied to the lifetime of the program and not of any given function or class instance. When should you use it? Don't. What is the purpose? Debugging data, mostly.

Generally, in C++, if you find yourself using static data, you've done it wrong. There are times when it's appropriate, but they're very rare.

羁〃客ぐ 2024-09-19 20:58:57

当 C++ 中的类中使用 static 时,其含义与 Java 中的含义大致相同。对于变量来说,这意味着所有类都存在该变量的一个实例,对于函数来说,这意味着该函数根本不会隐式访问 this 指针。

在 C 和 C++ 中,当 static 用于全局变量或函数时,意味着该变量只能在当前 C 或 C++ 文件中引用。换句话说,编译器不得为变量或函数生成任何重定位符号。

当局部函数中的变量旁边使用 static 时,这意味着该变量不会超出范围,但会在函数调用之间保留其值。该变量实际上成为只能从给定函数访问的全局变量。

When static is used in a class in C++, it means more or less the same thing that it does in Java. For variables it means that one one instance of the variable exists for all classes and for functions, it means that the function does not implicitly access the this pointer at all.

In C and C++ when static is used for a global variable or function, then it means that the variable may only be referenced in the current C or C++ file. In other words, the compiler must not generate any relocation symbols for the variable or function.

When static is used next to a variable in a local function, it means that the variable does not go out of scope but will retain its value from function-call to function-call. The variable become effectively a global variable that can only be accessed from the given function.

过去的过去 2024-09-19 20:58:57

静态类成员是与类本身关联的数据和函数,而不是与类的对象关联的数据和函数。

在下面的示例中,类 Fred 有一个静态数据成员 x_ 和一个实例数据成员 y_。无论创建多少个 Fred 对象(包括没有 Fred 对象),Fred::x_ 都只有一份副本,但每个 Fred 对象都有一个 y_。因此,x_ 被称为与该类相关联,而 y_ 被称为与该类的单个对象相关联。类似地,Fred 类有一个静态成员函数 f() 和一个实例成员函数 g()。

class Fred {
    public:
        static void f() throw();                           <-- 1
        void g() throw();                                  <-- 2
    protected:
        static int x_;                                     <-- 3
        int y_;                                            <-- 4
};

(1) 与类关联的成员函数

(2) 与类的单个对象关联的成员函数

(3) 与类关联的数据成员

(4) 与类的单个对象关联的数据成员

用法:< /strong>

当您想要记录创建的类的实例数量时,您可以使用静态变量。例如,在“Car”类中,每个 Car 实例可能有一个唯一的序列号(在本例中为 _y),并且公司可能希望跟踪生产的汽车数量(在本例中为 _x)。

Static class members are data and functions that are associated with the class itself, rather than with the objects of the class.

In the following example, class Fred has a static data member x_ and an instance data member y_. There is only one copy of Fred::x_ regardless of how many Fred objects are created (including no Fred objects), but there is one y_ per Fred object. Thus x_ is said to be associated with the class and y_ is said to be associated with an individual object of the class. Similarly class Fred has a static member function f() and an instance member function g().

class Fred {
    public:
        static void f() throw();                           <-- 1
        void g() throw();                                  <-- 2
    protected:
        static int x_;                                     <-- 3
        int y_;                                            <-- 4
};

(1) Member function associated with the class

(2) Member function associated with an individual object of the class

(3) Data member associated with the class

(4) Data member associated with an individual object of the class

Usage:

When you want to keep tract of the number of instances of a class created you use static variable. For example in a 'Car' class each Car instance may have a unique serial number(_y in this case) and the company may want to keep track of the number of cars produced(_x in this case).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文