IT 관련자료/C++
산술연산자 오버로딩(+,-,*,/ 등)
elkein
2022. 3. 2. 19:00
#include <iostream>
using namespace std;
class Cents
{
int _cents;
public:
Cents(int cents =0) { _cents = cents; }
int getCents() const { return _cents; }
int& getCents() { return _cents; }
Cents operator - (const Cents& c2)
{ //함수의 멤버로 들어왔으니 _cents를 직접 받을 수 있다.
return Cents(this->_cents - c2._cents);
}
//연산자를 오버로딩해주면 간편!!
//friend 함수를 사용해서 class안에 넣어버리기
friend Cents operator + (const Cents& c1, const Cents& c2)
{
return Cents(c1.getCents() + c2.getCents());
}
};
//c_out 이라는 곳에 파라미터를 받는것(레퍼런스로 ㅋㅋ)
void add(const Cents& c1, const Cents& c2, Cents& c_out)
{
c_out.getCents() = c1.getCents() + c2.getCents();
}
//요즘에는 파라미터 말고 리턴값으로 받도록 설계를 한다고 하심
Cents add2(const Cents& c1, const Cents& c2)
{
return Cents(c1.getCents() + c2.getCents());
}
//연산자를 오버로딩해주면 간편!!
//Cents operator + (const Cents& c1, const Cents& c2)
//{
// return Cents(c1.getCents() + c2.getCents());
//}
class Test_constructor
{
private:
int _cents;
int _test;
public:
Test_constructor(int cents, const int _test_in)
:_test(_test_in)
{
_cents = cents;
}
int getCents() const { return _cents; }
};
int main()
{
Cents cents1(6);
Cents cents2(8);
Cents sum;
add(cents1, cents2,sum);
cout << sum.getCents() << endl;
cout << add2(cents1, cents2).getCents() << endl;
//산술 연산자 오버로딩의 결과!
cout << (cents1 + cents2 + Cents(6) +Cents(10)).getCents() << endl;
// ?; :: sizeof . .* 등의 연산자는 오버로딩 불가
// ^ 연산자 우선순위가 매우 낮아서 오버로딩 하는거 비추
}