https://www.learncpp.com/cpp-tutorial/overloading-unary-operators/
positive (+), negative (-) and logical not (!) operators 는
모두 unary operator (단항 연산자) 이다
example:
#include <iostream>
class Cents
{
private:
int m_cents {};
public:
Cents(int cents): m_cents(cents) {}
// Overload -Cents as a member function
Cents operator-() const;
int getCents() const { return m_cents; }
};
// note: this function is a member function!
Cents Cents::operator-() const
{
return -m_cents; // since return type is a Cents, this does an implicit conversion from int to Cents using the Cents(int) constructor
}
int main()
{
const Cents nickle{ 5 };
std::cout << "A nickle of debt is worth " << (-nickle).getCents() << " cents\n";
return 0;
}
단항 연산자 -를 operator overloadin으로 member function으로 구현하고 있음을 볼 수 있다
이번에는 not 연잔자와 함께 구현된 예시를 보자
#include <iostream>
class Point
{
private:
double m_x {};
double m_y {};
double m_z {};
public:
Point(double x=0.0, double y=0.0, double z=0.0):
m_x{x}, m_y{y}, m_z{z}
{
}
// Convert a Point into its negative equivalent
Point operator- () const;
// Return true if the point is set at the origin
bool operator! () const;
double getX() const { return m_x; }
double getY() const { return m_y; }
double getZ() const { return m_z; }
};
// Convert a Point into its negative equivalent
Point Point::operator- () const
{
return { -m_x, -m_y, -m_z };
}
// Return true if the point is set at the origin, false otherwise
bool Point::operator! () const
{
return (m_x == 0.0 && m_y == 0.0 && m_z == 0.0);
}
int main()
{
Point point{}; // use default constructor to set to (0.0, 0.0, 0.0)
if (!point)
std::cout << "point is set at the origin.\n";
else
std::cout << "point is not set at the origin.\n";
return 0;
}
return 값은 bool로 point의 모든 member variable이 0.0이면 참을 반환한다