C++ static的所有用法及对应的代码示例

在 C++ 中,关键字 static 有几种不同的用途,主要用于管理存储类和访问类的范围。下面详细介绍 static 的每个用法,并提供相应的代码示例、代码解释以及运行结果。

1. 局部静态变量

static 用于函数内的局部变量时,它会使变量保持其值状态,即使在函数调用结束后也不会销毁。这样的变量只初始化一次,每次函数调用时保留其最后一次使用的值。

代码示例:

#include <iostream>
using namespace std;

void countFunction() {
    static int count = 0;
    count++;
    cout << "Count: " << count << endl;
}

int main() {
    countFunction();  // 输出 1
    countFunction();  // 输出 2
    countFunction();  // 输出 3
    return 0;
}

运行结果:

Count: 1
Count: 2
Count: 3

2. 全局静态变量

在函数外部使用 static 声明的全局变量或函数,限制了其链接性(可见性),使其只在定义它的文件中可见。

代码示例:

// file1.cpp
#include <iostream>
static int globalValue = 10;

void display() {
    std::cout << "Global Value in file1: " << globalValue << std::endl;
}

// file2.cpp
#include <iostream>
extern int globalValue;  // 编译错误,globalValue 在 file2 中不可见

int main() {
    display();
}

运行结果:

Global Value in file1: 10

(注意:这里的 “file2.cpp” 编译时将会报错,因为 globalValue 对它不可见)

3. 静态类成员变量

static 也可以用于类的成员变量。这种情况下,变量不属于任何特定的对象实例,而是类的所有实例共享的。它们必须在类外部初始化。

代码示例:

#include <iostream>
using namespace std;

class MyClass {
public:
    static int staticValue;
};

int MyClass::staticValue = 0;

int main() {
    MyClass::staticValue = 5;
    cout << "Static Value: " << MyClass::staticValue << endl;  // 输出 5

    MyClass obj1, obj2;
    obj1.staticValue = 2;
    cout << "Static Value from obj2: " << obj2.staticValue << endl;  // 输出 2
    return 0;
}

运行结果:

Static Value: 5
Static Value from obj2: 2

4. 静态类成员函数

类方法也可以声明为 static。这样的方法可以在没有任何对象实例的情况下调用,并且只能访问其类的静态成员。

代码示例:

#include <iostream>
using namespace std;

class MyClass {
public:
    static int staticValue;
    
    static void displayValue() {
        cout << "Static Value: " << staticValue << endl;
    }
};

int MyClass::staticValue = 10;

int main() {
    MyClass::displayValue();  // 输出 10
    return 0;
}

运行结果:

Static Value: 10

这些例子涵盖了 static 在 C++ 中的主要用法,有助于理解如何在不同情景中使用它以及其对程序行为的影响。

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Warren++

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值