C++基本中の基本その8
※自分用メモ
※引用元「ローベルのC++入門講座」
#include <iostream> #include <string> using namespace std; void obamaTerm(int &x) //int &xを変数にすることで「参照」という変数が作れる。 { if(2009 <= x && x <= 2016) x -= 2008; else x = 0; } void presidency() //ここのコーディングは結構めんどくさい。。。レベル上げたらもっと綺麗にする。 { int year; cout << "Enter a year: " << flush; cin >> year; obamaTerm(year); //この場合xはyearの参照になり、xを操作することでyearを操作することができる。 if(year == 1) { cout << "That year would be Obama's " << year << "st year as president." << endl; } else if(year == 2) { cout << "That year would be Obama's " << year << "nd year as president." << endl; } else if(year == 3) { cout << "That year would be Obama's " << year << "rd year as president." << endl; } else if(4 <= year && year <= 8) { cout << "That year would be Obama's " << year << "th year as president." << endl; } else { cout << "Obama was not president in that year." << endl; } } int main() { presidency(); presidency(); presidency(); presidency(); presidency(); return 0; }
結果
Enter a year: 2009 That year would be Obama's 1st year as president. Enter a year: 2010 That year would be Obama's 2nd year as president. Enter a year: 2011 That year would be Obama's 3rd year as president. Enter a year: 2015 That year would be Obama's 7th year as president. Enter a year: 1999 Obama was not president in that year.
・int &x
とすることで 参照 (pass by reference)
という特殊な変数になる。
・参照
によって x
が year
への参照になり、関数越しに変数を操作することができる。