関数オーバーロード
メニューを表示するにはスワイプしてください
関数のオーバーロードは、同じ名前で異なるパラメータを持つ複数の関数を同一スコープ内で定義することを可能にする機能。これにより、類似した処理を行う関数を、異なるデータ型やパラメータ数に対応して作成できる。オーバーロードはコードの可読性、再利用性、柔軟性を高める。
main.cpp
1234567891011121314151617181920212223242526#include <iostream> // Function with one integer parameter void processValue(int num) { std::cout << "Processing integer: " << num << std::endl; } // Overloaded function with one double parameter void processValue(double num) { std::cout << "Processing double: " << num << std::endl; } int main() { // Function calls with different data types int intValue = 5; double doubleValue = 3.14; // Calls the first version of `processValue` processValue(intValue); // Calls the second version of `processValue` processValue(doubleValue); }
これらの関数は同じ引数型を持つが、関数シグネチャ内で引数の順序が異なる。
main.cpp
1234567891011121314151617181920212223242526#include <iostream> // Overloaded function with a different number of arguments void processValue(int num, std::string text) { std::cout << "Integer and string: " << num << ", " << text << std::endl; } // Overloaded function with different arguments order void processValue(std::string text, int num) { std::cout << "String and integer: " << text << ", " << num << std::endl; } int main() { // Function calls with different data types and numbers of arguments int intValue = 5; std::string stringValue = "Hello"; // Calls the third version of processValue processValue(intValue, stringValue); // Calls the forth version of processValue processValue(stringValue, intValue); }
ノート
関数をオーバーロードするには、同じ名前である必要があります。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 1
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 1