下面为大家介绍在C++中定义常量的四种方式
第一种:使用关键字const声明的常量
#include <iostream>
using namespace std;
int main() {
const int day = 365;
cout << "一年有" << day << "天" << endl;
system("pause");
return 0;
}
第二种:使用constexpr定义常量表达式
#include <iostream>
using namespace std;
constexpr int getmouth() { return 4 * 7; }
int main() {
cout << "一个月有" << getmouth() << "天" << endl;
system("pause");
return 0;
}
第三种:枚举
#include <iostream>
using namespace std;
enum CardinalDirections
{
North = 25,
South,
East,
West
};
int main() {
cout << "显示方向" << endl;
cout << "North:" << North << endl;
cout << "South:" << South << endl;
cout << "East:" << East << endl;
cout << "West:" << West << endl;
CardinalDirections windDirection = South;
cout << windDirection << endl;
system("pause");
return 0;
}
第四种:使用#define定义常量
#include <iostream>
using namespace std;
#define day 7
int main() {
cout << "一个星期有" << day << "天" << endl;
system("pause");
return 0;
}