Sobrecarga de funciones
Desliza para mostrar el menú
La sobrecarga de funciones permite definir múltiples funciones con el mismo nombre pero diferentes parámetros dentro del mismo ámbito. Facilita la creación de funciones que realizan tareas similares pero pueden manejar distintos tipos de datos o cantidades de parámetros. La sobrecarga mejora la legibilidad, reutilización y flexibilidad del código.
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); }
Estas funciones tienen los mismos tipos de argumentos, pero estos argumentos tienen un orden diferente en la firma de la función.
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); }
Nota
Para sobrecargar la función, deben tener el mismo nombre.
¿Todo estuvo claro?
¡Gracias por tus comentarios!
Sección 4. Capítulo 1
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Sección 4. Capítulo 1