C++ - Static关键字怎么用

本文深入探讨了C++中static关键字在不同作用域(局部、全局、文件)下的含义,包括其作为访问控制特性在全局函数中的应用,以及在类成员变量和成员类中的新用途。

The static keyword is probably the most confusing keyword in the C++ language. This is because it has different meanings depending on where it is used.

(static很令人迷惑,因为在不同的地方有不同的用途)


You know, local variables (which have block scope) and global variables (which have program scope).
By default, local variables have automatic duration, which means they are destroyed when the block they are declared in goes out of scope.

(介绍scope -- program scope & block scope。)

The static keyword has another meaning when applied to global variables — it changes them from global scope to file scope. Because global variables are typically avoided by competent programmers, and file scope variables are just global variables limited to a single file, the static keyword is typically not used in this capacity.

(另一种跟static相关的scope -- file scope。即static用于global variable时的含义。)

static Is also used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.

(另一种跟static相关的scope -- file scope。即static用于global function时的含义。)

In a funcation, static variables keep their values and are not destroyed even after they go out of scope.

(static用于local variables of functions时的含义。)


C++ introduces two new uses for the static keyword when applied to classes: static member variables, and static member classes.

(C++中引入static另外2种用途 -- static member variables & static member classes)


By making the member variables static, only one copy exists for all objects, rather than a copy for each object instantiated.
(static用于class member variables时的含义。)
Static data members are not part of objects of a given class type; they are separate objects. Consequently, it is better to think of static members as belonging to the class itself, not the objects of the class.
As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope. These static members have external linkage. The following example illustrates this:


//-------------------------------------------------------------------------------------------------//

// static_data_members.cpp
class BufferedOutput
{
public:
   // Return number of bytes written by any object of this class.
   short BytesWritten()
   {
      return bytecount;
   }

   // Reset the counter.
   static void ResetCount()
   {
      bytecount = 0;
   }

   // Static member declaration.
   static long bytecount;
};

// Define bytecount in file scope.
long BufferedOutput::bytecount;

int main()
{

}

//-------------------------------------------------------------------------------------------------//


<think>我们正在讨论C++中的static关键字。根据引用内容,staticC++中用于修饰变量、函数和类成员,主要作用是控制存储方式和作用范围。下面我将详细解释static的几种用法。 1. **静态局部变量**:在函数内部使用static修饰的局部变量。这种变量在程序运行期间只初始化一次,且生命周期持续到程序结束。每次函数调用时,该变量保持上次调用结束时的值。例如: ```cpp void func() { static int count = 0; // 只初始化一次 count++; cout << count << endl; } ``` 调用`func()`三次会输出1, 2, 3。因为`count`在函数调用之间保持其值。 2. **静态全局变量/函数**:在全局作用域(函数外部)使用static修饰的变量或函数,其作用域仅限于定义它的文件(编译单元)。这样避免了命名冲突,也实现了信息隐藏。例如: ```cpp // file1.cpp static int globalVar = 42; // 只在file1.cpp中可见 // file2.cpp extern int globalVar; // 错误!无法访问file1.cpp中的globalVar ``` 3. **静态成员变量**:在类内部用static修饰的成员变量。它属于整个类,而不是某个对象,因此被所有对象共享。必须在类外定义和初始化(除非是C++17引入的inline static)。例如: ```cpp class MyClass { public: static int count; // 声明 }; int MyClass::count = 0; // 定义和初始化 // 使用:MyClass::count 或 obj.count(不推荐通过对象访问) ``` 4. **静态成员函数**:用static修饰的成员函数。它属于类而不是对象,因此不能访问非静态成员(因为没有this指针)。可以通过类名直接调用。例如: ```cpp class MyClass { public: static void printCount() { cout << count << endl; // 正确,count是静态成员变量 // cout << data; // 错误!不能访问非静态成员 } private: int data; static int count; }; ``` 总结static关键字的作用: - 延长局部变量的生命周期(使其具有静态存储期) - 限制全局变量/函数的作用域(文件作用域) - 实现类的成员变量和函数由所有对象共享 这些特性使得static在模块化设计、数据共享和状态保持等场景中非常有用。 §§相关问题§§ 1. 静态成员变量在类中如何初始化? 2. 为什么静态成员函数不能访问非静态成员变量? 3. 静态局部变量和全局静态变量有什么区别? 4. 在多线程环境下使用static变量需要注意什么?</think>### C++中`static`关键字的作用详解 `static`关键字C++中有多种用法,主要控制变量和函数的**存储方式**和**作用范围**。以下是核心作用: --- #### 1. **静态局部变量** 在函数内部声明,生命周期延长至程序结束,且**只初始化一次**: ```cpp void counter() { static int count = 0; // 只初始化一次 count++; std::cout << count << "\n"; } // 调用 counter() 三次输出:1, 2, 3 ``` - **特点**:函数退出后值仍保留,下次调用时沿用上次的值[^3]。 --- #### 2. **静态全局变量/函数** 在全局作用域使用`static`,限制作用域为**当前文件**: ```cpp // file1.cpp static int globalVar = 100; // 仅file1.cpp可见 static void helper() { ... } // 仅file1.cpp可调用 ``` - **作用**:避免多文件编译时的命名冲突,实现模块化封装[^1][^3]。 --- #### 3. **静态成员变量** 在类中声明,被**所有对象共享**: ```cpp class MyClass { public: static int sharedCount; // 声明 }; int MyClass::sharedCount = 0; // 类外定义初始化 ``` - **特点**: - 不属于任何对象,通过`类名::变量名`访问(如`MyClass::sharedCount`)。 - 替代全局变量,避免命名污染[^2]。 --- #### 4. **静态成员函数** 属于类而非对象,**无`this`指针**: ```cpp class MyClass { public: static void printCount() { std::cout << sharedCount; // 只能访问静态成员 } }; // 调用:MyClass::printCount(); ``` - **限制**: - 不能访问非静态成员(因无对象实例)[^2][^3]。 --- ### 总结对比 | 类型 | 作用域 | 生命周期 | 关键特性 | |---------------------|----------------------------|----------------|------------------------------| | 静态局部变量 | 函数内部 | 程序结束 | 只初始化一次,保留状态 | | 静态全局变量/函数 | 当前文件 | 程序结束 | 避免跨文件命名冲突 | | 静态成员变量 | 类作用域 | 程序结束 | 所有对象共享,类外初始化 | | 静态成员函数 | 类作用域 | - | 无`this`指针,仅访问静态成员 | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值