티스토리 뷰

함수 오버로딩

같은 이름의 함수두 개 이상 정의하여 사용하는 것
함수명은 같으나, parameter list 부분이 달라야 함
함수 type(X), parameter 순서(O), type(O), 개수(O), 구성 etc... parameter list가 달라야 함.
pointer의 const 여부도 다른 type으로 인식함!
parameter type 자동형변환에 의한 호출이 가능함. 단, 대표타입에 한해서

Default Parameter

함수의 매개변수에 기본값을 정의할 수 있다.

int Function(int, int, int = 1, int = 2);

int main()
{
    Function(1,2,3,4);    //default parameter 사용 X
    Function(1,2,3);    //(1,2,3,2)
    Function(1,2);        //(1,2,1,2)
    Function(1);        //error
    Function();            //error
    Function(1,2,,4);    //error -> 이런 구조는 불가능
}

Default Parameter를 지정하면 그 이후의 parameter는 모두 Default Parameter로 지정되어야 함!

void func(int a = 10, int b, int c);    
void func(int a = 10, int b = 20, int c);    
void func(int a, int b = 20, int c);
void func(int(a = 10; int b, int c = 30);

위의 경우는 모두 불가능. default parameter를 부분적으로 사용하고 싶다면 다 뒤로 빼야 한다.

함수 overlading과 default parameter를 같이 사용 시, 형태의 모호함이 발생한다면 컴파일 오류가 난다.

void prn(char *);
void prn(char *, int = 10);    //error!!

실습 with ChatGPT

Low Difficulty

Write a C++ program that defines a function called print that takes a single argument of type int and prints it to the console. Then overload the print function to take a single argument of type double and prints it to the console as well. Use default parameter for the double version of print, so that the user can call the function with just one argument and it will be treated as a double by default.

Code

/*
Write a C++ program that defines a function called print that takes a single argument of type int and prints it to the console. 
Then overload the print function to take a single argument of type double and prints it to the console as well. 
Use default parameter for the double version of print, 
so that the user can call the function with just one argument and it will be treated as a double by default.
*/
#include <iostream>
using namespace std;

void print(int n)
{
    cout << "int print" << endl;
    cout << n << endl;
}

void print(double n = 0.0)
{
    cout << "double print" << endl;
    cout << n << endl;
}

int main()
{
    int num = 3;
    double num2 = 2.5;
    print(3);
    print(num2);
    print();
    print(num);
}

출력 결과

int print
3
double print
2.5
double print
0
int print
3

Medium Difficulty

Write a C++ program that defines a function called sum that takes two arguments of type int and returns their sum.
Then overload the sum function to take three arguments of type int and return their sum.
Use default parameters for the third argument of the sum function,
so that the user can call the function with just two arguments and the third argument will be assumed to be 0 by default.

Code

/*
Write a C++ program that defines a function called sum that takes two arguments of type int and returns their sum. 
Then overload the sum function to take three arguments of type int and return their sum. 
Use default parameters for the third argument of the sum function, 
so that the user can call the function with just two arguments and the third argument will be assumed to be 0 by default.
*/
#include<iostream>
using namespace std;
int sum(int a, int b, int c=0)
{
    return a+b+c;
}

int main()
{
    cout << sum(1,2) << endl;
    cout << sum(2,3,4) << endl;
}

출력 결과

3
9

High Difficulty

Write a C++ program that defines a class called Rectangle with private member variables width and height. The class should have the following public member functions:

A default constructor that sets both width and height to 0.
A constructor that takes two arguments of type int and sets width and height to those values.
A function called area that takes no arguments and returns the area of the rectangle (width times height).
Overload the + operator to allow adding two Rectangle objects together, which should return a new Rectangle object whose width and height are the sums of the width and height of the two operands, respectively.
Overload the << operator to allow outputting a Rectangle object to the console. This should print the values of width and height of the Rectangle object.

Code

/*
Write a C++ program that defines a class called Rectangle with private member variables width and height. 
The class should have the following public member functions:

A default constructor that sets both width and height to 0.
A constructor that takes two arguments of type int and sets width and height to those values.
A function called area that takes no arguments and returns the area of the rectangle (width times height).
Overload the + operator to allow adding two Rectangle objects together, 
which should return a new Rectangle object whose width and height are the sums of the width and height of the two operands, respectively.
Overload the << operator to allow outputting a Rectangle object to the console. 
This should print the values of width and height of the Rectangle object.
*/

#include <iostream>
using namespace std;

class Rectangle {
    int height, width;
    public:
        Rectangle() : height(0), width(0) { }
        Rectangle(int a, int b) : height(a), width(b) { }
        int area()
        {
            return height * width;
        }
        Rectangle operator+(const Rectangle &obj);
        friend ostream& operator<<(ostream& os, const Rectangle &obj);
};

Rectangle Rectangle::operator+(const Rectangle &obj)
{
    Rectangle temp(height + obj.height, width + obj.width);
    return temp;    
}

ostream& operator<<(ostream& os, const Rectangle &obj)
{
    os << "height : " << obj.height << ", width : " << obj.width << endl;
    return os;
}

int main()
{
    Rectangle rect1;
    cout << rect1;
    Rectangle rect2(2, 3);
    Rectangle rect3(1, 1);
    cout << rect2;
    cout << rect2.area() << endl;
    Rectangle rect4 = rect2 + rect3;
    cout << rect4.area() << endl;
}

실행 결과

height : 0, width : 0
height : 2, width : 3
6
12

갑자기 연산자 오버로딩을 시켜서 좀 당황하였다.

'■ C++' 카테고리의 다른 글

자주쓰지만 까먹는 것들  (0) 2023.11.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함