Sobrecarga de Funções
Deslize para mostrar o menu
A sobrecarga de funções permite definir várias funções com o mesmo nome, mas com parâmetros diferentes dentro do mesmo escopo. Isso possibilita criar funções que executam tarefas semelhantes, mas que podem lidar com diferentes tipos de dados ou quantidades de parâmetros. A sobrecarga aumenta a legibilidade, reutilização e flexibilidade do 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); }
Essas funções possuem os mesmos tipos de argumentos, mas esses argumentos estão em ordem diferente na assinatura da função.
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 sobrecarregar a função, elas devem ter o mesmo nome.
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 4. Capítulo 1
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Seção 4. Capítulo 1