본문 바로가기
카테고리 없음

연산자 오버로딩의 3가지 형태

by 느억맘 2021. 11. 25.

3가지 구현중 1가지만 있으면 된다.

using namespace std;
//산술 연산자 오버로딩
class Cents
{
	int m_value;

public:
	Cents(const int& value)
	{
		m_value = value;
	}

	const int& getValue() const
	{
		return m_value;
	}

	const void setValue(const int& value)
	{
		m_value = value;
	}

// 1. Cents 의 매개함수의 형태
	 int operator +(const Cents& c2)
	{
		return Cents(this->m_value + c2.m_value).getValue();
	}

// 2. Cetnts 내부에 있지만 friend 로 인해 외부함수나 다름없는놈 
	friend int operator +(const Cents& c1, const Cents& c2)
	{
		return Cents(c1.m_value + c2.m_value).getValue();
	}
};

// 3. 외부함수 즉 전역함수
int operator +(const Cents& c1,const Cents& c2)
{
	return Cents(c1.getValue() + c2.getValue()).getValue();
}

int main()
{
	Cents c1(22);
	Cents c2(10);
	
	//cout << add(c1, c2) << endl;

	//cout << add(Cents(22), Cents(10)) << endl;

	cout << c1 + c2 << endl;

	cout << Cents(22) + Cents(434) << endl;
}