SlideShare a Scribd company logo
1 of 17
Download to read offline
13. 연산자 오버로딩
차례
• 객체 연산
• 연산자 오버로딩

2/14
객체 연산
• 허수 클래스를 정의하고, 객체를 생성하여 허수 덧셈을
실행하기
클래스 이름: ImaginaryNumber
멤버 변수:
실수부와 허수부의 실수 (허수부의 실수는 0이 아닌 실수)
멤버 함수:
생성자 1: 실수부가 0, 허수부가 1로 초기화
생성자 2: 실수부와 허수부를 매개변수로 전달하여 값을 지정
실수부 값과 허수부 값을 각각 전달받는 함수
실수부 값과 허수부 값을 객체 외부로 전달하는 각각의 함수
허수 형태로 문자열을 작성하는 함수

3/14
소스 13-1 (ch13_ImaginaryNumber.h)
#ifndef _IMAGINARY_
#define _IMAGINARY_
#include <iostream>
#include <string>
using namespace std;
class ImaginaryNumber
{
public:
ImaginaryNumber();
ImaginaryNumber(const double a, const double b);
void SetA(const double a);
void SetB(const double b);
double GetA();
double GetB();
string GetImaginaryNumber();
private:
};
#else
#endif

double a; //실수부
double b; //허수부 (b≠0)

4/14
허수의 덧셈
멤버 함수 추가
ImaginaryNumber AddImaginary(const ImaginaryNumber ima);
 자기자신과 매개변수를 더해서 결과값을 리턴함
멤버 함수 정의
ImaginaryNumber ImaginaryNumber::AddImaginary(const ImaginaryNumber
ima)
{
ImaginaryNumber res;
res.a=this->a+ima.a;
res.b=this->b+ima.b;
}

객체 덧셈을 위한 함수 정의

return res;

5/14
허수 덧셈 테스트
소스 13-5 (ch13_02.cpp)
#include "ch13_ImaginaryNumber.h"
int main()
{
ImaginaryNumber ima1(4.2,5.1);
ImaginaryNumber ima2;
ImaginaryNumber ima3;
ima2.SetA(7.2);
ima2.SetB(9.6);
ima3=ima1.AddImaginary(ima2); //ima1과 ima2의 덧셈 결과가 리턴, ima3에 할당
cout << "( " << ima1.GetImaginaryNumber() << " ) + ";
cout << "( " << ima2.GetImaginaryNumber() << " ) = ";
cout << ima3.GetImaginaryNumber() << endl;
}

return 0;
6/14
연산자 오버로딩 1
• 연산자 오버로딩
• 연산 대상에 대한 연산자 재정의
3+4  정수의 덧셈 연산 가능함!!!
class TEST
{
….
};
TEST a, b;
a+b  연산 불가능, TEST의 객체를 대상으로 하는 덧셈 연산 오버로딩해야함
string str1(“computer”), str2(“science”);
str1+str2  연산 가능, string 객체를 대상으로 하는 덧셈 연산이 오버로딩되어 있
음

7/14
연산자 오버로딩 2
• 연산자 오버로딩 함수 프로토타입
함수반환형 operator 연산자 (연산대상);
ImaginaryNumber 클래스에 덧셈 연산 함수를 정의하면~
함수 선언 :
ImaginaryNumber operator+(const ImaginaryNumber object);
함수 정의 :
ImaginaryNumber ImaginaryNumber::operator+(const ImaginaryNumber object) //연산
자 오버로딩에 의해 추가된 연산자 함수
{
ImaginaryNumber res;
res.a=this->a+object.a;
res.b=this->b+object.b;
}

return res;
8/14
소스 13-6 (ch13_03.cpp)
허수의 덧셈 객체 연산자 오버로딩 테스트~
#include "ch13_ImaginaryNumber.h"
int main()
{
ImaginaryNumber ima1(2.7,6.3);
ImaginaryNumber ima2;
ImaginaryNumber ima3;
ima2.SetA(7.2);
ima2.SetB(9.6);
ima3=ima1+ima2; //연산자 오버로딩으로 인해 덧셈 연산자 사용 가능!!
cout << "( " << ima1.GetImaginaryNumber() << " ) + ";
cout << "( " << ima2.GetImaginaryNumber() << " ) = ";
cout << ima3.GetImaginaryNumber() << endl;
}

return 0;
9/14
증감 연산자 오버로딩
• 증감 연산자
• 선 증감 : ++a, --a
• 후 증감 : a++, a-클래스형 operator++( ); //선 증감 연산자 오버로딩
클래스형 operator++(int dummy); //후 증감 연산자 오버로딩
ImaginaryNumber 클래스의 증가 연산자 오버로딩
ImaginaryNumber operator++(void);
ImaginaryNumber operator++(int dummy);

10/14
소스 13-9 (ch13_ImanginaryNumber.cpp)
ImaginaryNumber ImaginaryNumber::operator++(void) //연산자 오버로딩에
의해 추가된 연산자 함수
{
this->a++;
return *this;
}
ImaginaryNumber ImaginaryNumber::operator++(int dummy)
{
this->b++;
return *this;
}

11/14
오버로딩 가능한 연산자

+

^

=

*=

|=

==

||

->

-

&

<

/=

<<

!=

++

[]

*

|

>

%=

>>

<=

--

()

/

~

+=

^=

>>=

>=

->*

new

%

!

-=

&=

<<=

&&

,

delete

12/25
실습 – 시간 클래스 정의하기
클래스 이름: Time
멤버 변수: 시, 분, 초를 나타내는 부호 없는 정수와 초 단위로 시간을 나타냄
멤버 함수 :
생성자1: 매개변수 없이 멤버 변수를 0으로 초기화
생성자2: 시, 분, 초의 멤버 변숫값을 매개변수로 전달하여 초기화
초 단위로 시간을 나타내는 멤버 변숫값을 계산하는 멤버 함수 CalSecond( )
각 멤버 변숫값을 설정하는 멤버 함수
각 멤버 변숫값을 외부로 전달할 수 있는 멤버 함수
'00시 00분 00초' 형태로 외부에 전달하는 멤버 함수

13/14
소스 13-10 (ch13_Time.h)
#ifndef _TIME_
#define _TIME_
#include <iostream>
#include <string>
#define HOUR_SEC 3600
#define MIN_SEC 60
using namespace std;

class Time
{
public :
Time();
Time(const int hour, const int min, const int sec);
void SetHour(const int hour);
void SetMin(const int min);
void SetSec(const int sec);
int GetHour();
int GetMin();
int GetSec();
int CalSec();
string ShowTime();
private :
};

int hour, min, sec;
int t_sec;

#else
#endif
14/14
TIME 클래스에 <=, >= 오버로딩하기
멤버 함수 선언
bool operator<=(Time timeObj);
bool operator>=(Time timeObj);
멤버 함수 정의
bool Time::operator<=(Time timeObj)
{
this->CalSec();
timeObj.CalSec();

}

bool Time::operator>=(Time timeObj)
{
this->CalSec();
timeObj.CalSec();

if (this->t_sec<=timeObj.t_sec)
if (thisreturn true;
>t_sec>=timeObj.t_sec)
else
return true;
return false;
else
return false;
}
15/14
소스 13-16 (ch13_06.cpp) Time 클래스 테스트
#include "ch13_Time.h"
int main()
{

Time t1(7,30,20);
cout << t1.ShowTime() << endl;
cout << "시간 - 초단위 : " << t1.CalSec() << endl;
Time t2(4,50,23);
if (t1>=t2)
else
if (t1<=t2)
else

}

cout << t1.ShowTime() << "이 " << t2.ShowTime() << "보다 크거나 같다!!" << endl;
cout << t2.ShowTime() << "이 " << t1.ShowTime() << "보다 크거나 같다!!" << endl;
cout << t2.ShowTime() << "이 " << t1.ShowTime() << "보다 크거나 같다!!" << endl;
cout << t1.ShowTime() << "이 " << t2.ShowTime() << "보다 크거나 같다!!" << endl;

return 0;

16/14
연산자 오버로딩과 FRIEND
#include <iostream>
using namespace std;
class NUMBOX
{
private:
int num1, num2;
public:
NUMBOX(int num1, int num2) : num1(num1),
num2(num2) { }
void ShowNumber()
{
cout << "num1: " << num1 << ", num2: "
<< num2 << endl;
}
NUMBOX operator+(int num)
{
return NUMBOX(num1+num, num2+num);
}
friend NUMBOX operator+(int num, NUMBOX&
ref);
};

NUMBOX operator+(int num, NUMBOX& ref)
{
return ref + num;
}
int main()
{
NUMBOX nb1(10, 20);
NUMBOX result = 10 + nb1 + 40;
nb1.ShowNumber();
result.ShowNumber();
}

17/25

More Related Content

What's hot

[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍흥배 최
 
Startup JavaScript 4 - 객체
Startup JavaScript 4 - 객체Startup JavaScript 4 - 객체
Startup JavaScript 4 - 객체Circulus
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기Yongha Yoo
 
Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Circulus
 
Cpp 0x kimRyungee
Cpp 0x kimRyungeeCpp 0x kimRyungee
Cpp 0x kimRyungeescor7910
 
React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기Kim Hunmin
 
[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)NAVER D2
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성HyeonSeok Choi
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택JinTaek Seo
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initializationEunjoo Im
 
2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자Circulus
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기Jongwook Choi
 
Swift3 typecasting nested_type
Swift3 typecasting nested_typeSwift3 typecasting nested_type
Swift3 typecasting nested_typeEunjoo Im
 

What's hot (20)

[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
[KGC 2012]Boost.asio를 이용한 네트웍 프로그래밍
 
C++11
C++11C++11
C++11
 
Boost
BoostBoost
Boost
 
Startup JavaScript 4 - 객체
Startup JavaScript 4 - 객체Startup JavaScript 4 - 객체
Startup JavaScript 4 - 객체
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기
 
Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저Startup JavaScript 6 - 함수, 스코프, 클로저
Startup JavaScript 6 - 함수, 스코프, 클로저
 
Cpp 0x kimRyungee
Cpp 0x kimRyungeeCpp 0x kimRyungee
Cpp 0x kimRyungee
 
React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기React로 TDD 쵸큼 맛보기
React로 TDD 쵸큼 맛보기
 
[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)[devil's camp] - 알고리즘 대회와 STL (박인서)
[devil's camp] - 알고리즘 대회와 STL (박인서)
 
5 swift 기초함수
5 swift 기초함수5 swift 기초함수
5 swift 기초함수
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
 
6 swift 고급함수
6 swift 고급함수6 swift 고급함수
6 swift 고급함수
 
iOS 메모리관리
iOS 메모리관리iOS 메모리관리
iOS 메모리관리
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initialization
 
2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자2.Startup JavaScript - 연산자
2.Startup JavaScript - 연산자
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기
 
Swift3 typecasting nested_type
Swift3 typecasting nested_typeSwift3 typecasting nested_type
Swift3 typecasting nested_type
 
WTL 소개
WTL 소개WTL 소개
WTL 소개
 

Similar to W14 chap13

스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍Young-Beom Rhee
 
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원탑크리에듀(구로디지털단지역3번출구 2분거리)
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리은숙 이
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿유석 남
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기지수 윤
 
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Isaac Jeon
 
More effective c++ chapter1,2
More effective c++ chapter1,2More effective c++ chapter1,2
More effective c++ chapter1,2문익 장
 
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Senchamniktw
 
C# Game Server
C# Game ServerC# Game Server
C# Game Serverlactrious
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] FunctionsBill Kim
 
ECMA Script 5 & 6
ECMA Script 5 & 6ECMA Script 5 & 6
ECMA Script 5 & 6sewoo lee
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)문익 장
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택JinTaek Seo
 
일단 시작하는 코틀린
일단 시작하는 코틀린일단 시작하는 코틀린
일단 시작하는 코틀린Park JoongSoo
 
08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)유석 남
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리ETRIBE_STG
 

Similar to W14 chap13 (20)

스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
 
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기
 
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
 
06장 함수
06장 함수06장 함수
06장 함수
 
More effective c++ chapter1,2
More effective c++ chapter1,2More effective c++ chapter1,2
More effective c++ chapter1,2
 
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
한국 커뮤니티 데이 트랙2, 세션2 JavaScript 성능향상과 Sencha
 
6 function
6 function6 function
6 function
 
C# Game Server
C# Game ServerC# Game Server
C# Game Server
 
강의자료4
강의자료4강의자료4
강의자료4
 
[Swift] Functions
[Swift] Functions[Swift] Functions
[Swift] Functions
 
ECMA Script 5 & 6
ECMA Script 5 & 6ECMA Script 5 & 6
ECMA Script 5 & 6
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)
 
Multithread programming 20151206_서진택
Multithread programming 20151206_서진택Multithread programming 20151206_서진택
Multithread programming 20151206_서진택
 
일단 시작하는 코틀린
일단 시작하는 코틀린일단 시작하는 코틀린
일단 시작하는 코틀린
 
08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)
 
Tdd 4장
Tdd 4장Tdd 4장
Tdd 4장
 
Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리Javascript 완벽 가이드 정리
Javascript 완벽 가이드 정리
 

More from 웅식 전

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation웅식 전
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array웅식 전
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer웅식 전
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 

More from 웅식 전 (20)

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
13. structure
13. structure13. structure
13. structure
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
9. pointer
9. pointer9. pointer
9. pointer
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
6. function
6. function6. function
6. function
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
4. loop
4. loop4. loop
4. loop
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 

W14 chap13

  • 2. 차례 • 객체 연산 • 연산자 오버로딩 2/14
  • 3. 객체 연산 • 허수 클래스를 정의하고, 객체를 생성하여 허수 덧셈을 실행하기 클래스 이름: ImaginaryNumber 멤버 변수: 실수부와 허수부의 실수 (허수부의 실수는 0이 아닌 실수) 멤버 함수: 생성자 1: 실수부가 0, 허수부가 1로 초기화 생성자 2: 실수부와 허수부를 매개변수로 전달하여 값을 지정 실수부 값과 허수부 값을 각각 전달받는 함수 실수부 값과 허수부 값을 객체 외부로 전달하는 각각의 함수 허수 형태로 문자열을 작성하는 함수 3/14
  • 4. 소스 13-1 (ch13_ImaginaryNumber.h) #ifndef _IMAGINARY_ #define _IMAGINARY_ #include <iostream> #include <string> using namespace std; class ImaginaryNumber { public: ImaginaryNumber(); ImaginaryNumber(const double a, const double b); void SetA(const double a); void SetB(const double b); double GetA(); double GetB(); string GetImaginaryNumber(); private: }; #else #endif double a; //실수부 double b; //허수부 (b≠0) 4/14
  • 5. 허수의 덧셈 멤버 함수 추가 ImaginaryNumber AddImaginary(const ImaginaryNumber ima);  자기자신과 매개변수를 더해서 결과값을 리턴함 멤버 함수 정의 ImaginaryNumber ImaginaryNumber::AddImaginary(const ImaginaryNumber ima) { ImaginaryNumber res; res.a=this->a+ima.a; res.b=this->b+ima.b; } 객체 덧셈을 위한 함수 정의 return res; 5/14
  • 6. 허수 덧셈 테스트 소스 13-5 (ch13_02.cpp) #include "ch13_ImaginaryNumber.h" int main() { ImaginaryNumber ima1(4.2,5.1); ImaginaryNumber ima2; ImaginaryNumber ima3; ima2.SetA(7.2); ima2.SetB(9.6); ima3=ima1.AddImaginary(ima2); //ima1과 ima2의 덧셈 결과가 리턴, ima3에 할당 cout << "( " << ima1.GetImaginaryNumber() << " ) + "; cout << "( " << ima2.GetImaginaryNumber() << " ) = "; cout << ima3.GetImaginaryNumber() << endl; } return 0; 6/14
  • 7. 연산자 오버로딩 1 • 연산자 오버로딩 • 연산 대상에 대한 연산자 재정의 3+4  정수의 덧셈 연산 가능함!!! class TEST { …. }; TEST a, b; a+b  연산 불가능, TEST의 객체를 대상으로 하는 덧셈 연산 오버로딩해야함 string str1(“computer”), str2(“science”); str1+str2  연산 가능, string 객체를 대상으로 하는 덧셈 연산이 오버로딩되어 있 음 7/14
  • 8. 연산자 오버로딩 2 • 연산자 오버로딩 함수 프로토타입 함수반환형 operator 연산자 (연산대상); ImaginaryNumber 클래스에 덧셈 연산 함수를 정의하면~ 함수 선언 : ImaginaryNumber operator+(const ImaginaryNumber object); 함수 정의 : ImaginaryNumber ImaginaryNumber::operator+(const ImaginaryNumber object) //연산 자 오버로딩에 의해 추가된 연산자 함수 { ImaginaryNumber res; res.a=this->a+object.a; res.b=this->b+object.b; } return res; 8/14
  • 9. 소스 13-6 (ch13_03.cpp) 허수의 덧셈 객체 연산자 오버로딩 테스트~ #include "ch13_ImaginaryNumber.h" int main() { ImaginaryNumber ima1(2.7,6.3); ImaginaryNumber ima2; ImaginaryNumber ima3; ima2.SetA(7.2); ima2.SetB(9.6); ima3=ima1+ima2; //연산자 오버로딩으로 인해 덧셈 연산자 사용 가능!! cout << "( " << ima1.GetImaginaryNumber() << " ) + "; cout << "( " << ima2.GetImaginaryNumber() << " ) = "; cout << ima3.GetImaginaryNumber() << endl; } return 0; 9/14
  • 10. 증감 연산자 오버로딩 • 증감 연산자 • 선 증감 : ++a, --a • 후 증감 : a++, a-클래스형 operator++( ); //선 증감 연산자 오버로딩 클래스형 operator++(int dummy); //후 증감 연산자 오버로딩 ImaginaryNumber 클래스의 증가 연산자 오버로딩 ImaginaryNumber operator++(void); ImaginaryNumber operator++(int dummy); 10/14
  • 11. 소스 13-9 (ch13_ImanginaryNumber.cpp) ImaginaryNumber ImaginaryNumber::operator++(void) //연산자 오버로딩에 의해 추가된 연산자 함수 { this->a++; return *this; } ImaginaryNumber ImaginaryNumber::operator++(int dummy) { this->b++; return *this; } 11/14
  • 13. 실습 – 시간 클래스 정의하기 클래스 이름: Time 멤버 변수: 시, 분, 초를 나타내는 부호 없는 정수와 초 단위로 시간을 나타냄 멤버 함수 : 생성자1: 매개변수 없이 멤버 변수를 0으로 초기화 생성자2: 시, 분, 초의 멤버 변숫값을 매개변수로 전달하여 초기화 초 단위로 시간을 나타내는 멤버 변숫값을 계산하는 멤버 함수 CalSecond( ) 각 멤버 변숫값을 설정하는 멤버 함수 각 멤버 변숫값을 외부로 전달할 수 있는 멤버 함수 '00시 00분 00초' 형태로 외부에 전달하는 멤버 함수 13/14
  • 14. 소스 13-10 (ch13_Time.h) #ifndef _TIME_ #define _TIME_ #include <iostream> #include <string> #define HOUR_SEC 3600 #define MIN_SEC 60 using namespace std; class Time { public : Time(); Time(const int hour, const int min, const int sec); void SetHour(const int hour); void SetMin(const int min); void SetSec(const int sec); int GetHour(); int GetMin(); int GetSec(); int CalSec(); string ShowTime(); private : }; int hour, min, sec; int t_sec; #else #endif 14/14
  • 15. TIME 클래스에 <=, >= 오버로딩하기 멤버 함수 선언 bool operator<=(Time timeObj); bool operator>=(Time timeObj); 멤버 함수 정의 bool Time::operator<=(Time timeObj) { this->CalSec(); timeObj.CalSec(); } bool Time::operator>=(Time timeObj) { this->CalSec(); timeObj.CalSec(); if (this->t_sec<=timeObj.t_sec) if (thisreturn true; >t_sec>=timeObj.t_sec) else return true; return false; else return false; } 15/14
  • 16. 소스 13-16 (ch13_06.cpp) Time 클래스 테스트 #include "ch13_Time.h" int main() { Time t1(7,30,20); cout << t1.ShowTime() << endl; cout << "시간 - 초단위 : " << t1.CalSec() << endl; Time t2(4,50,23); if (t1>=t2) else if (t1<=t2) else } cout << t1.ShowTime() << "이 " << t2.ShowTime() << "보다 크거나 같다!!" << endl; cout << t2.ShowTime() << "이 " << t1.ShowTime() << "보다 크거나 같다!!" << endl; cout << t2.ShowTime() << "이 " << t1.ShowTime() << "보다 크거나 같다!!" << endl; cout << t1.ShowTime() << "이 " << t2.ShowTime() << "보다 크거나 같다!!" << endl; return 0; 16/14
  • 17. 연산자 오버로딩과 FRIEND #include <iostream> using namespace std; class NUMBOX { private: int num1, num2; public: NUMBOX(int num1, int num2) : num1(num1), num2(num2) { } void ShowNumber() { cout << "num1: " << num1 << ", num2: " << num2 << endl; } NUMBOX operator+(int num) { return NUMBOX(num1+num, num2+num); } friend NUMBOX operator+(int num, NUMBOX& ref); }; NUMBOX operator+(int num, NUMBOX& ref) { return ref + num; } int main() { NUMBOX nb1(10, 20); NUMBOX result = 10 + nb1 + 40; nb1.ShowNumber(); result.ShowNumber(); } 17/25