機能#
導入#
関数はC++プログラミングの基本的な構成要素であり、特定のタスクを実行するように設計された、再利用可能で効率的なコード断片にコードスニペットをパッケージ化します。関数はプログラム内で複数回呼び出すことができるため、コードの構成が容易になり、コードの重複を避けることができます。また、関数を使用することでコードのデバッグも容易になります。
このページでは、C++における関数使用の基本について説明します。内容は以下のとおりです。
関数の構造と構文 — 戻り値の型、名前、パラメータなど、C++ で関数を記述する方法。
関数プロトタイプ — プロトタイプ関数とは何か、そしてなぜ使用されるのか。
関数の定義と呼び出し — プログラムから関数を作成して呼び出す方法。
戻り値 — 関数が呼び出し元にデータを返す方法。
コールバック関数 — 関数を他の関数に渡して、イベントに応じて自動的に呼び出す方法。
デフォルト引数を持つ関数 — 引数が指定されていない場合に、パラメーターにデフォルト値を設定する方法。
関数構造と構文#
C++では、関数は戻り値の型、名前、および引数を指定して宣言する必要があります。基本的な構文は次のとおりです。
return_type function_name(parameters) {
// Code to execute when the function is called
return result; // Optional, used to return a value
}
機能部品 |
説明 |
|---|---|
|
The data type that the function returns, some common options are:
|
|
関数名。 |
|
オプション。カンマ区切りの型付きパラメータのリスト。形式は |
|
オプション。関数が返す値。関数の |
Note: A function must always be declared before it is called, or you must provide a function prototype.
関数プロトタイプ#
C++では、コードは上から下へと読み込まれます。つまり、関数は呼び出される前にコンパイラに認識されていなければなりません。
関数プロトタイプを使用すると、完全なコードを書く前に関数を使用できます。これにより、プログラムの先頭付近に main() を残しておき、関数定義を後で配置して整理しやすく、読みやすくすることができます。
プロトタイプがない場合、 main()より上のすべての関数を定義する必要があり、プロジェクトが大きくなるにつれて追跡が難しくなる可能性があります。
関数プロトタイプを定義します(
int main()の外側)// The function's prototype void greeting();関数を呼び出す
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); greeting(); }関数本体を記述します
void greeting() { Brain.Screen.print("Hello!"); }
関数の定義と呼び出し#
Functions with No Parameters#
関数が入力値を必要としない場合は、引数なしで定義できます。関数が値を返さない場合は、戻り値の型として void を使用してください。
関数を定義します (
int main()の外側)// Define a function to display a message void greeting() { Brain.Screen.print("Hello!"); }関数を呼び出す
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Call the function to display the message greeting(); }
Functions with Parameters#
関数にパラメータを追加することもできます。これにより、関数が使用する情報を渡すことができます。
注: テキストは、C スタイルの文字列 (const char*) または C++ 文字列 (std::string ) を使用して渡すことができます。
関数を定義します (
int main()の外側)// Define a function with a parameter void namedGreeting(const char* name) { Brain.Screen.print("Hello, %s!", name); }パラメータを内部に含んだ関数を呼び出します
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Call the function to display the message namedGreeting("Stranger"); }
戻り値#
関数は、 return キーワードを使用して呼び出し元にデータを返すことができます。これにより、出力を取得してプロジェクト内で使用できます。
関数を定義します (
int main()の外側)// Define a function that multiplies numbers by 2 int timesTwo(int number) { return number * 2; }パラメータを内部に含んだ関数を呼び出します
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Display the return value Brain.Screen.print("%d", timesTwo(2)); }
参照による譲渡#
By default, C++ passes function parameters by value, meaning the function receives a copy of the original variable. Changes made inside the function do not affect the original value.
関数を定義します (
int main()の外側)// Add 1 to the number void addOne(int number) { number++; }パラメータを内部に含んだ関数を呼び出します
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); int value = 5; addOne(value); // "value" will still be 5 }
関数が元の 変数 を変更できるようにするには、 & 記号を使用して参照渡しでパラメータを渡すことができます。
関数を定義します (
int main()の外側)// Add 1 to the number void addOne(int& number) { number++; }パラメータを内部に含んだ関数を呼び出します
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); int value = 5; addOne(value); // "value" will now be 6 }
Passing by reference allows functions to update variables defined outside the function without returning a value.
コールバック関数#
コールバック関数とは、別の関数に渡され、特定のイベントが発生したときに自動的に呼び出される関数のことです。
コールバックは、ボタンの押下やセンサーの更新などのイベントでよく使用されます。
自分で関数を呼び出す代わりに、プロジェクトがイベント発生時に自動的に関数を呼び出します。
コールバック関数を定義します(
int main()の外側)// Create a callback function void onPressed() { Brain.Screen.print("Screen pressed!"); }コールバックを登録する
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Call onPressed whenever the screen is pressed Brain.Screen.pressed(onPressed); }
Callback Signatures#
すべてのコールバック関数は、以下を定義する特定のシグネチャに従う必要があります。
戻り値の型
パラメータの数
パラメータの型
必要な署名はAPIによって決定されます。コールバック関数はこの署名と完全に一致する必要があります。
// This callback function cannot include any parameters
void callback(void);
// This callback function includes four parameters
void callback(axisType axis, double x, double y, double z);
パラメータ名は説明的なものであり、変更可能だが、戻り値の型、パラメータの順序、およびパラメータの型は完全に一致しなければならない。
デフォルト引数を持つ関数#
関数は、1つまたは複数のパラメータに対してデフォルト値を定義できます。デフォルト引数は、関数呼び出し時にそのパラメータに値が指定されていない場合に使用されます。
デフォルト引数のルール:
デフォルト引数は、関数の定義における最後のパラメータでなければなりません。
パラメータにデフォルト値が設定されると、それ以降のすべてのパラメータにもデフォルト値が設定されなければなりません。
関数がその プロトタイプ でデフォルト引数を指定している場合、それらのデフォルト値は関数定義で再度指定してはなりません。
関数を定義します (
int main()の外側)// Required parameter first, default parameter last void greeting(const char* name, int repeatCount = 1) { for (int i = 0; i < repeatCount; i++) { Brain.Screen.print("Hello, %s!", name); Brain.Screen.newLine(); } }関数を呼び出す
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Say what name to greet (EXP) and // use default value for repeatCount (1) greeting("EXP"); Brain.Screen.newLine(); // Overrides the default value to 3 greeting("EXP", 3); }
// Required parameter first, default parameter last
void greeting(const char* name, int repeatCount = 1) {
for (int i = 0; i < repeatCount; i++) {
Brain.Screen.print("Hello, %s!", name);
Brain.Screen.newLine();
}
}
int main() {
vexcodeInit();
// Say what name to greet (EXP) and
// use default value for repeatCount (1)
greeting("EXP");
Brain.Screen.newLine();
// Overrides the default value to 3
greeting("EXP", 3);
}