>>> 1. 局部变量
void func() { static int count = 0; // 只会初始化一次 count++; printf("%d\n", count);}
>>> 2. 全局变量
static int globalVar = 0; // 只在当前文件可见
>>> 3. 修饰函数
static void helperFunction() { // 只能在当前文件中调用}
>>> 4. 修饰指针
static int* ptr; // 指针本身是静态的,但它指向的内容可以动态变化
>>> 1. 局部变量
void func() { const int value = 10; // value = 20; // 错误:试图修改只读变量}
>>> 2. 全局变量
const int globalValue = 100;
>>> 3. 修饰函数参数
void func(const int* ptr) { // *ptr = 20; // 错误:试图修改只读指针指向的值}
>>> 4. 修饰指针
const int* p1; // 指向常量 int 的指针int* const p2 = &value; // 常量指针const int* const p3 = &value; // 常量指针指向常量const int value1 = 5;const int value2 = 10;const int* p1 = &value1; // 合法// *p1 = 6; // 错误:不能修改常量p1 = &value2; // 合法:可以改变指针指向int value = 5; // 定义整型变量 valueint* const p2 = &value; // p2 是一个常量指针,指向 value 的地址printf("Original value: %d\n", *p2); // 输出 value 的值*p2 = 10; // 修改 p2 指向的值,即修改 value 的值printf("Modified value: %d\n", *p2); // 输出修改后的值// p2 = &anotherValue; // 这行代码将会导致编译错误,因为不能改变常量指针的地址 const int value = 5;const int* const p3 = &value; // 合法// *p3 = 10; // 错误:不能修改常量// p3 = &anotherValue; // 错误:不能改变常量指针地址
>>> 1. 静态常量全局变量 当 static 和 const 结合用于全局变量时,表示这个变量只能在定义它的文件内可见,并且其值是不可修改的。
#include <stdio.h>static const int maxSize = 100; // 静态常量全局变量void printMaxSize() { printf("Max Size: %d\n", maxSize);}int main() { printMaxSize(); // maxSize = 200; // 错误:不能修改 const 变量 return 0;}
>>> 2. 静态常量局部变量 当使用 static 和 const 修饰局部变量时,表示该变量的值在函数调用之间保持不变,并且它是不可修改的。
#include <stdio.h>void func() { static const int countLimit = 5; // 静态常量局部变量 // countLimit++; // 错误:不能修改 const 变量 printf("Count Limit: %d\n", countLimit);}int main() { func(); func(); return 0;}
>>> 3. 静态常量指针 你可以创建一个静态常量指针,表示该指针在整个程序执行期间保持有效,同时指针指向的值不可修改。
#include <stdio.h>void func() { static int value = 10; static const int* const ptr = &value; // 静态常量指针 // *ptr = 20; // 错误:不能修改 const 指针指向的值 // ptr = &anotherValue; // 错误:不能修改常量指针的地址 printf("Value: %d\n", *ptr);}int main() { func(); return 0;}
>>> 1. 静态成员函数 在类中,使用 static 修饰的成员函数称为静态成员函数。它们属于类本身,而不是类的某个对象。静态成员函数可以在不创建类实例的情况下被调用。 特点:
this
指针,因为它不属于任何对象。#include <iostream>class MyClass {public: static int count; // 静态成员变量 MyClass() { count++; } static void showCount() { // 静态成员函数 std::cout << "Count: " << count << std::endl; }};// 初始化静态成员变量int MyClass::count = 0;int main() { MyClass obj1; MyClass obj2; MyClass::showCount(); // 调用静态成员函数,不需要实例化对象 return 0;}
>>> 2. 静态局部函数 虽然 C++ 中的静态函数通常指的是静态成员函数,但如果在函数外部定义静态函数,这种函数的作用域仅限于它被定义的文件。这意味着其他文件无法访问这个函数。
#include <iostream>static void localFunction() { // 静态局部函数 std::cout << "This is a static local function." << std::endl;}int main() { localFunction(); // 调用静态局部函数 return 0;}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。