9. Utilization of Class

지니🧸·2023년 2월 25일
0

C++

목록 보기
9/10

본 문서는 인프런의 [하루 10분|C++] 누구나 쉽게 배우는 C++ 프로그래밍 입문 강의를 공부하며 작성한 개인 노트입니다.

🥠 연산자 오버로딩

연산자 오버로딩

  • 다형 특징
  • 함수 오버로딩과 같은 방식
    (예)* - 변수 앞에 붙으면 주소, 변수 사이에서는 곱셈

Time 클래스 생성 및 활용

  • 클래스
    헤더파일/time.h
#ifndef TIMEH
#define TIMEH

class Time
{
private:
	int hours;
    int mins;
    
public:
	Time();
    Time(int, int);
    void addHours(int);
    void addMins(int);
    void sum(Time&);
    void show();
    ~Time();
};

#endif
  • 정의
    func.cpp
#include "time.h"

Time::Time()
{
	hours = 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 %= 60;
};
Time Time::sum(Time&) {
	Time sum;
    sum.mins = mins + t.mins;
    sum.hours = hours + t.hours;
    sum.hours += sum.mins / 60;
    sum.mins %= 60;
};
void Time::show(){
	std::cout << "시간: " << hours << endl;
    std::cout << "분: " << mins << endl;
};
Time::~Time();
  • 활용
#include <iostream>

using namespace std;

int main() {
	
    Time day1(1, 40);
    Time day2(2, 30);
    
    day1.show();
    day2.show();
    
    Time total;
    total = day1.sum(day2);
    total show();
    
    return 0;
}

sum 함수를 +로 바꿔보자

선언

함수명을 operator(연산자)로 셋팅
(예) operator+

class Time
{
private:
	...
public:
	...
    Time operator+(Time&);
};

정의

Time Time::operator+(Time&) {
	Time sum;
    sum.mins = mins + t.mins;
    sum.hours = hours + t.hours;
    sum.hours += sum.mins / 60;
    sum.mins %= 60;
};

활용

...
int main() {
	...
    
    Time total1;
    total = day1.operator+(day2);
    
    Time total2;
    total2 = day1 + day2;
}

오버로딩 할 수 있는 연산자

&, *, +, -

🥟 프렌드

C++ Friend

함수를 어떤 클래스에 대해 friend으로 만들면 그 함수는 클래스의 멤버 함수와 동등한 접근 권한을 가짐

  • 필요 이유: 어떤 클래스의 이항 연산자를 오버라이딩할 경우
    • 이항 연산자: 두 개의 피연산자를 요구하는 연산자
  • 특징: 멤버 연산자가 아니기에 점(.) 또는 화살표(->) 연산자로 호출 불가

선언

Time.h

...
public:
	...
    friend Time operator*(int, Time&);
};

정의

func.cpp

...
Time operator*(int n) {
	Time result;
    long resultMin = t.hours * n * 60 +t.mins * n;
    result.hours = resultMin / 60;
    result.mins = resultMin % 60;
    return result;
}

활용

main.cpp

int main() {
	Time t1(1, 20);
    Time t2;
    
    t2 = 3 * t1; //t2 = operator*(3);
    t2.show();
}
  • 함수 안의 매개변수 순서가 바뀌면 동작되지 않을 수도? > 유의해서 코딩하자

🍮 Interface

interface: 특정 기능을 구현할 것을 약속한 추상 형식

  • 좁은 의미: 순수 가상 함수만을 갖는 클래스
  • 넓은 의미: 앞으로 프로그래밍을 어떻게 짤 것인가에 대한 약속

🥮 << 연산자 오버로딩

<<: 스트링 추출 연산자 또는 꺽새 연산자

  • iostream에 정의되어있는 함수
  • (ex) cout << "Hello";

예시

선언

time.h

...
public:
	...
    friend std::ostream& operator <<(std::ostream&, Time&);
};

정의

func.cpp

std::ostream& operator<<(std::ostream& os, Time& t) {
	os << t.hours << "시간 " << t.mins << "분";
    return os;
}
  • << 연산자는 좌항의 값으로 os 객체를 요구하고 있기 때문에 리턴형이 os의 참조임

사용

int main() {
	
    Time t1(3, 45);
    
	// t1.show(); 대체
    cout << t1;
    
    return 0;
}
profile
우당탕탕

0개의 댓글