[ 공 부 ]/[ C + + ]

Operator의 사용

HiStar__ 2019. 11. 13. 01:10

////////////////////////////////////////////////////////////////////////////////////////////////

// class(struct) 키워드로 사용자 정의 자료형을 만든다.
//
////////////////////////////////////////////////////////////////////////////////////////////////
#include 
#include 
#include 
#include "SaveCode.h"


class INT {
int val;

public:
INT() {};
INT(int v) : val{ v } {};

~INT() {};


// 입출력 연산자는 class의 friend로 선언하자
friend std::ostream& operator << (std::ostream& , const INT& );
friend std::ifstream& operator >> (std::ifstream&, INT&);

// ++ INT : prefix increment operator 
INT&operator ++() {
++val; // 나를 증가 시키고
return *this; // 나스스로 자신을 리턴
}

// INT ++ : postfix increment operator
// temp의 크기가 클 경우 임시변수가 크기 때문에 좋은 코드가 아니다.
INT operator++(int rhs) {
INT temp{ *this }; // 임시 객체
++(*this); // 그 후에 나를 1 증가 시킨다.
return temp; // 실제로 증가하지 않는다.
}

};


std::ostream& operator << (std::ostream& os, const INT& rfs) {
os << rfs.val;
return os;
}

std::ifstream& operator >> (std::ifstream& is, INT& rfs) {
is >> rfs.val;
// is.read()  바이트 Binary로 읽을 경우 속도가 증가한다.

return is;
}




int main() {
CodeSave("Main.cpp"); // 코드 저장용 함수


// ++ a 와 a ++ 의 차이점
INT a{ 10 };

++a; // a.operator++()
a++; // a.operator++(INT)




// int b = a ++;
// b는 10이 나온다. 

std::cout << a << std::endl;

return 0;
}