IT 관련자료/C++

단항연산자 오버로딩 (!, -)

elkein 2022. 3. 2. 20:01

여기서 -는 단항연산자로 부호바꿀때...!

x=1 >> -x 이런거

#include <iostream>

using namespace std;

class Cents
{
private:
	int _cents;

public:
	Cents(int cents = 0) { _cents = cents; }
	int getCents() const { return _cents; }
	int& getCents() { return _cents; }
	
	//부호 바꿔주는 단항 연산자..!
	Cents operator - () const
	{
		return Cents(-_cents);
	}

	bool operator ! () const
	{
		//프로그래밍 목적에 따라서 알아서 설정
		return (_cents == 0) ? true : false;
	}


	friend std::ostream& operator << (std::ostream& out, const Cents& cents)
	{
		cout << cents._cents;
		return out;
	}
};
int main()
{
	Cents cents1(6);
	Cents cents2(0);

	//Cents 타입
	auto temp01 = cents1;
	//bool 타입
	auto temp02 = !cents1;
	//!cent는 0일때 트루, !돈 = 돈없음 = 돈없는거 맞음 이런식으로 의도
	cout << !cents1 << " " << !cents2 << endl;

	cout << cents1 << endl;
	cout << -cents1 << endl;
	cout << -Cents(-10) << endl;

	int a = 3;

	cout << -a << endl;
	cout << !a << endl;


	return 0;
}