温馨提示×

如何在C++中定义和使用constant

c++
小樊
82
2024-09-14 09:54:39
栏目: 编程语言

在C++中,可以使用const关键字来定义常量

  1. 定义一个常量:
#include<iostream>

int main() {
    const int my_constant = 42; // 定义一个整数常量并赋值为42
    std::cout << "The value of my_constant is: " << my_constant<< std::endl;
    return 0;
}
  1. 使用常量表达式(C++11及更高版本):
#include<iostream>

int main() {
    constexpr int my_constant = 42; // 定义一个编译时常量并赋值为42
    std::cout << "The value of my_constant is: " << my_constant<< std::endl;
    return 0;
}
  1. 使用常量引用:
#include<iostream>

void print_value(const int& value) {
    std::cout << "The value is: "<< value<< std::endl;
}

int main() {
    const int my_constant = 42;
    print_value(my_constant); // 将常量传递给函数
    return 0;
}

注意:在C++中,常量的值在程序运行期间不能被修改。尝试修改常量的值会导致编译错误。

0