c++ static const
作者:野牛程序员:2023-07-28 08:50:45 C++阅读 2634
在 C++ 中,static const 是用于声明静态常量的组合。静态常量是指在程序运行期间其值不能被修改的常量,而静态性质意味着它在内存中只有一个副本,不会被实例化的每个对象所拥有。
static const 常量通常用于声明类的常量成员或全局常量,以及在类内部用于定义常量表达式。
以下是一些 static const 常量的示例:
类的静态常量成员:
class MyClass {
public:
static const int MAX_VALUE = 100; // 类的静态常量成员
};
int main() {
// 访问类的静态常量成员
std::cout << MyClass::MAX_VALUE << std::endl; // 输出:100
return 0;
}全局静态常量:
static const double PI = 3.14159; // 全局静态常量
int main() {
// 访问全局静态常量
std::cout << PI << std::endl; // 输出:3.14159
return 0;
}类内部使用静态常量:
class MyClass {
public:
static const int ARRAY_SIZE = 5; // 类的静态常量成员
void printArray() {
int arr[ARRAY_SIZE] = {1, 2, 3, 4, 5};
for (int i = 0; i < ARRAY_SIZE; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
};
int main() {
MyClass obj;
obj.printArray(); // 输出:1 2 3 4 5
return 0;
}请注意,在类内部声明静态常量成员时,需要在类外部对它进行定义和初始化。通常在头文件中声明,在源文件中进行定义和初始化。
// MyClass.h 头文件
class MyClass {
public:
static const int MAX_VALUE; // 类的静态常量成员声明
};
// MyClass.cpp 源文件
const int MyClass::MAX_VALUE = 100; // 类的静态常量成员定义和初始化总结起来,static const 是 C++ 中用于声明静态常量的组合,它可以用于类的常量成员、全局常量以及类内部定义常量表达式。静态常量在程序运行期间保持不变,且只有一个副本,不会被多次实例化。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++中static关键字的作用
- 下一篇:c++ class struct区别
