본문 바로가기
로봇/C++

C++ 오버로딩 Overloading Functions

by 33곰탱 2025. 1. 9.

C++에서는 같은 이름의 함수여도 사용 가능!

 

핵심 정리: 함수 오버로딩

  • 함수 이름은 같아도 매개변수의 타입 또는 매개변수의 개수가 다르면 여러 번 정의 가능.
  • 함수 호출 시, 컴파일러가 매개변수의 타입과 개수를 보고 적절한 함수를 자동으로 선택.
void display(int n);
void display(double d);
void display(std::string s);
void display(std::string s, std::string t);
void display(std::vector<int> v);
void display(std::vector<std::string> v);
#include <iostream>
#include <vector>
#include <string>

// 정수를 출력하는 함수
void display(int n) {
    std::cout << "Integer: " << n << std::endl;
}

// 실수를 출력하는 함수
void display(double d) {
    std::cout << "Double: " << d << std::endl;
}

// 문자열을 출력하는 함수
void display(std::string s) {
    std::cout << "String: " << s << std::endl;
}

// 두 개의 문자열을 출력하는 함수
void display(std::string s, std::string t) {
    std::cout << "String 1: " << s << ", String 2: " << t << std::endl;
}

// 정수 벡터를 출력하는 함수
void display(std::vector<int> v) {
    std::cout << "Vector of Integers: ";
    for (int i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
}

// 문자열 벡터를 출력하는 함수
void display(std::vector<std::string> v) {
    std::cout << "Vector of Strings: ";
    for (const std::string& str : v) {
        std::cout << str << " ";
    }
    std::cout << std::endl;
}
int main() {
    // 정수 출력
    display(42);

    // 실수 출력
    display(3.14);

    // 문자열 출력
    display("Hello");

    // 두 개의 문자열 출력
    display("Hello", "World");

    // 정수 벡터 출력
    std::vector<int> int_vec = {1, 2, 3, 4, 5};
    display(int_vec);

    // 문자열 벡터 출력
    std::vector<std::string> string_vec = {"Alice", "Bob", "Charlie"};
    display(string_vec);

    return 0;
}
Integer: 42
Double: 3.14
String: Hello
String 1: Hello, String 2: World
Vector of Integers: 1 2 3 4 5
Vector of Strings: Alice Bob Charlie

'로봇 > C++' 카테고리의 다른 글

Declaring pointer & Dynamic Memory Allowcation  (0) 2025.02.05
C++ Scope rules 스코프 룰  (1) 2025.01.09
C++ string 문자열  (1) 2025.01.09
C++ Range-based for Loop  (1) 2025.01.09
C++ 벡터  (0) 2025.01.09