阅读量:66
在C++中,可以使用const关键字来定义常量
- 定义一个常量:
#include
int main() {
const int my_constant = 42; // 定义一个整数常量并赋值为42
std::cout << "The value of my_constant is: " << my class="hljs-keyword">return 0;
}
- 使用常量表达式(C++11及更高版本):
#include
int main() {
constexpr int my_constant = 42; // 定义一个编译时常量并赋值为42
std::cout << "The value of my_constant is: " << my class="hljs-keyword">return 0;
}
- 使用常量引用:
#include
void print_value(const int& value) {
std::cout << "The value is: "<< value class="hljs-function">int main() {
const int my_constant = 42;
print_value(my_constant); // 将常量传递给函数
return 0;
}
注意:在C++中,常量的值在程序运行期间不能被修改。尝试修改常量的值会导致编译错误。