定数を定義するいくつかの方法
1407 ワード
C++で定数を定義する4つの方法をご紹介します
1つ目:キーワードconstを使用して宣言される定数
2つ目:constexprを使用して定数式を定義する
3つ目:列挙
4つ目:#defineを使用して定数を定義する
1つ目:キーワードconstを使用して宣言される定数
#include
using namespace std;
int main() {
const int day = 365;
cout << " " << day << " " << endl;
system("pause");
return 0;
}
2つ目:constexprを使用して定数式を定義する
#include
using namespace std;
constexpr int getmouth() { return 4 * 7; }
int main() {
cout << " " << getmouth() << " " << endl;
system("pause");
return 0;
}
3つ目:列挙
#include
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;
}
4つ目:#defineを使用して定数を定義する
#include
using namespace std;
#define day 7
int main() {
cout << " " << day << " " << endl;
system("pause");
return 0;
}