c++ static

static 关键字在C++中有多种用途,取决于它的使用位置。它可以用于变量、函数和成员函数。以下是不同上下文中的详细说明:

1. 静态全局变量和静态函数
  • 作用域:文件范围
  • 说明:当static用于全局变量或函数时,该变量或函数的作用域限制在定义它的文件中。
// file1.cpp
static int globalVar = 10;

static void staticFunction() {
   std::cout << "This is a static function." << std::endl;
}

void nonStaticFunction() {
   std::cout << "This is a non-static function." << std::endl;
}
// file2.cpp
extern int globalVar; // Error: globalVar is not visible here

void callStaticFunction() {
   staticFunction(); // Error: staticFunction is not visible here
}
2. 静态局部变量
  • 作用域:块范围(局部)
  • 生命周期:程序生命周期
  • 说明:当static用于函数内部的局部变量时,该变量在函数的多次调用之间保持其值。
void counter() {
   static int count = 0;
   ++count;
   std::cout << "Count: " << count << std::endl;
}

int main() {
   counter(); // Output: Count: 1
   counter(); // Output: Count: 2
   return 0;
}
3. 静态成员变量
  • 作用域:类范围
  • 生命周期:程序生命周期
  • 说明:当static用于类的成员变量时,该变量在所有对象间共享,且该变量不属于某个具体的对象,而是属于类。
class MyClass {
public:
   static int staticVar;
   static void staticMethod() {
       std::cout << "Static variable: " << staticVar << std::endl;
   }
};

int MyClass::staticVar = 0;

int main() {
   MyClass::staticVar = 5;
   MyClass::staticMethod(); // Output: Static variable: 5
   return 0;
}
4. 静态成员函数
  • 作用域:类范围
  • 说明:当static用于类的成员函数时,该函数可以在不创建对象的情况下调用,且不能访问非静态成员变量。
class MyClass {
public:
   static void staticMethod() {
       std::cout << "This is a static method." << std::endl;
   }
};

int main() {
   MyClass::staticMethod(); // Output: This is a static method.
   return 0;
}

总结

  • 静态全局变量和静态函数:作用域限制在定义它们的文件内,其他文件不可见。
  • 静态局部变量:在函数内部声明,函数多次调用间保持值。
  • 静态成员变量:属于类而非具体对象,所有对象间共享。
  • 静态成员函数:可以在不创建对象的情况下调用,不能访问非静态成员。
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值