c++ 단항 연산자 오버로딩 하기
728x90
#include <iostream> using namespace std; class Cents { private: int m_cents; public: Cents(int cents= 0) { m_cents = cents; } int getCents() const { return m_cents; } int& getCents() { return m_cents; } };
Cents 클래스를 만들었습니다. 처음으로 할 것은 입출력 operator 를 오버로딩하는 것 입니다.
friend std::ostream& operator << (std::ostream &out, const Cents ¢s) { out << cents.m_cents; return out; }
class 내부에서 정의 했기 때문에 friend를 사용했고 cents의 값을 바꾸지 않을 것이기 때문에 const를 사용했습니다.
int main() { Cents cents1(8); Cents cents2(7); cout << cents1 << endl; return 0; }

- 연산자와 ! 연산자를 오버로딩 해보겠습니다.
Cents operator - () const { return Cents(-m_cents); } bool operator ! () const { return (m_cents == 0) ? true : false; }
int main() { Cents cents1(8); Cents cents2(0); auto temp = !cents1; cout << temp << endl; cout << -cents1 << endl; cout << -Cents(-20) << endl; return 0; }

728x90
'C++ > c++ - 따라하며 배우는 c++' 카테고리의 다른 글
증감연산자 오버로딩 (0) | 2020.11.12 |
---|---|
c++ 비교 연산자 오버로딩 하기 (1) | 2020.11.05 |
c++ 익명 객체 (anonymous) (0) | 2020.10.30 |
c++ 친구 함수와 클래스 friend (0) | 2020.10.30 |
c++ static member function (정적 멤버 함수) (0) | 2020.10.29 |
댓글
이 글 공유하기
다른 글
-
증감연산자 오버로딩
증감연산자 오버로딩
2020.11.12 -
c++ 비교 연산자 오버로딩 하기
c++ 비교 연산자 오버로딩 하기
2020.11.05 -
c++ 익명 객체 (anonymous)
c++ 익명 객체 (anonymous)
2020.10.30 -
c++ 친구 함수와 클래스 friend
c++ 친구 함수와 클래스 friend
2020.10.30
댓글을 사용할 수 없습니다.