728x90

1. 핵심 요약

1-1. 정의

연산자 오버로딩이란?

사용자 정의 데이터 타입(클래스)에 대한 연산자 동작을 redefine & expand

 C++ 객체 지향 프로그래밍의 핵심 원칙 하나인 다형성(polymorphism) 구현

 

- 다양한 연산자(예: +, -, *, /, ==, != 등)에 대해 사용됨

- 기존 연산자는 주로 특정 데이터타입에 국한되어 사용됨. 그러나 연산자 오버로딩을 통해, 사용자 정의 클래스의 객체를 일반적인 데이터 타입처럼 사용할 수 있음

 

*오류 방지하려면, 연산자의 의미와 클래스에 대한 연산 규칙을 명확히 이해해야

 

1-2. 연산자 오버로딩의 형식

- 연산자 오버로딩은 연산자(operator)를 정의한 클래스 내에서 진행됨

 

반환_타입 operator 연산자_이름(매개변수_목록) {

    // 연산을 정의한 코드

}

 

1-3. 연산자 오버로딩의 (일반화된?) 예시

- 클래스 내부에 연산자 오버로딩 정의

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r, double i) : real(r), imag(i) {}

    Complex operator+(const Complex& other) {
        return Complex(real + other.real, imag + other.imag);
    }
};

// Complex 클래스는 + 연산자를 오버로딩하여 두 개의 복소수를 더할 수 있도록 함.

- 연산자 오버로딩의 사용

Complex a(2.0, 3.0);
Complex b(1.0, 2.0);
Complex c = a + b; // + 연산자가 오버로딩되어 두 복소수를 더함

// a + b는 연산자 오버로딩된 + 연산자에 의해 두 Complex 객체가 더해짐

2. 구체적인 예시

2-1. 예시 요약

헤더파일에서

Time operator+(Time&);

함수 정의 파일에서

Time Time::operator+(Time& time){
    Time temp;
    temp.mins = mins + time.mins;
    temp.hours += temp.mins / 60;
    temp.mins %= 60;

    return temp;
}

main 파일에서

    Time total;
    total = day1.operator+(day2);

2-2. 예시 전문

 

1. time.h

#include<iostream>

#ifndef FIRE_C_TIME_H
#define FIRE_C_TIME_H

using namespace std;

class Time{
private:
    int hours;
    int mins;
public:
    Time(); //클래스 생성자 //함수 오버로딩
    Time(int, int); //함수 오버로딩
    void addHours(int);
    void addMins(int);
//    Time sum(Time&);
    Time operator+(Time&);
    void show();
    ~Time(); //클래스 파괴자
};

#endif //FIRE_C_TIME_H

2. time_func.cpp

#include "time.h"

Time::Time(){
    hours = 0;
    mins = 0;
}

Time::Time(int h, int m) {
    hours = h;
    mins = m;
}

void Time::addHours(int h) {
    hours += h;
}

void Time::addMins(int m) {
    mins += m;
    hours += mins / 60;
    mins = mins % 60;
}

// Time Time::sum(Time& time){
//    Time temp;
//    temp.mins = mins + time.mins;
//    temp.hours += temp.mins / 60;
//    temp.mins %= 60;
//
//    return temp;
//}

Time Time::operator+(Time& time){
    Time temp;
    temp.mins = mins + time.mins;
    temp.hours += temp.mins / 60;
    temp.mins %= 60;

    return temp;
}

void Time::show(){
    cout << hours << "시간 " << mins << "분" << endl;
}

Time::~Time(){

}

3. main.cpp

#include "time.h"
#include "time_func.cpp"

int main() {
    Time day1(1, 40);
    Time day2(2, 30);

    day1.show();
    day2.show();

    //오버로딩한 연산자 사용 방법 (1)
    Time total;
    total = day1.operator+(day2);
    //기존에 만들었던 sum 함수 역할을 수행하는 연산자 오버로딩 하려면
    //함수 있던 자리에 'operator' , '오버로딩 할 연산자'의 연속으로 표현하면 됨

    //오버로딩한 연산자 사용 방법 (2)
    Time total2;
    total2 = day1 + day2; //혹은 아예 연산자만 사용해도 됨

    total.show();
    total2.show();

    return 0;
}

/*1시간 40분
2시간 30분
1시간 10분
1시간 10분*/

 

728x90

+ Recent posts