https://www.learncpp.com/cpp-tutorial/overloading-operators-using-normal-functions/
우리는 이전 섹션에서 friend를 활용한 operator overloading에 대해서 배웠다
friend function은 클래스 멤버에 direct로 접근할 수 있으므로 편리하다
하지만 private 접근이 필요하지 않은 경우 friend function을 쓸 필요가 없다
이런 경우에는 normal function으로 operator overloading도 가능하다
#include <iostream>
class Cents
{
private:
int m_cents{};
public:
Cents(int cents)
: m_cents{ cents }
{}
int getCents() const { return m_cents; }
};
// note: this function is not a member function nor a friend function!
Cents operator+(const Cents& c1, const Cents& c2)
{
// use the Cents constructor and operator+(int, int)
// we don't need direct access to private members here
return Cents{ c1.getCents() + c2.getCents() };
}
int main()
{
Cents cents1{ 6 };
Cents cents2{ 8 };
Cents centsSum{ cents1 + cents2 };
std::cout << "I have " << centsSum.getCents() << " cents.\n";
return 0;
}
위의 경우 member function을 활용해 normal function으로 operator overloading을 구현했다
이에 파일 분리를 적용하면 다음과 같이 구성할 수 있다
Cents.h:
#ifndef CENTS_H
#define CENTS_H
class Cents
{
private:
int m_cents{};
public:
Cents(int cents)
: m_cents{ cents }
{}
int getCents() const { return m_cents; }
};
// Need to explicitly provide prototype for operator+ so uses of operator+ in other files know this overload exists
Cents operator+(const Cents& c1, const Cents& c2);
#endif
Cents.cpp:
#include "Cents.h"
// note: this function is not a member function nor a friend function!
Cents operator+(const Cents& c1, const Cents& c2)
{
// use the Cents constructor and operator+(int, int)
// we don't need direct access to private members here
return { c1.getCents() + c2.getCents() };
}
main.cpp
#include "Cents.h"
#include <iostream>
int main()
{
Cents cents1{ 6 };
Cents cents2{ 8 };
Cents centsSum{ cents1 + cents2 }; // without the prototype in Cents.h, this would fail to compile
std::cout << "I have " << centsSum.getCents() << " cents.\n";
return 0;
}
일반적으로 normal function으로 가능한 경우라면 friend를 사용하는 것보다 normal function을 사용하는 것이 선호된다
그렇다고 normal function을 사용하기 위해 member function을 새로 정의하면서까지 friend function을 사용하지 않을 필요는 없다