// C++ 常量示例代码
#include <iostream>
using namespace std;
int main() {
// 1. 使用 const 关键字定义常量
const int MAX_SIZE = 100;
cout << "MAX_SIZE: " << MAX_SIZE << endl;
// 2. 使用 #define 定义宏常量
#define PI 3.14159
cout << "PI: " << PI << endl;
// 3. 使用 constexpr 定义编译时常量表达式
constexpr int square(int x) {
return x * x;
}
cout << "Square of 5: " << square(5) << endl;
// 4. 字符串常量
const char* greeting = "Hello, World!";
cout << "Greeting: " << greeting << endl;
return 0;
}
const
关键字:用于定义常量,确保变量的值在程序运行期间不会被修改。例如 const int MAX_SIZE = 100;
。#define
预处理指令:用于定义宏常量,通常用于简单的替换操作。例如 #define PI 3.14159
。constexpr
关键字:用于定义编译时常量表达式,确保在编译时计算结果。例如 constexpr int square(int x)
。const char*
或 std::string
来定义字符串常量,确保字符串内容不可变。例如 const char* greeting = "Hello, World!";
。这些方法都可以用来定义常量,具体选择哪种方式取决于应用场景和需求。
上一篇:c++中const
下一篇:c++指针和引用的区别
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站