연산자 오버로딩
operator overloading
기본 문법
ReturnType operator Op(ArgumentType) {
// 구현
}실습 예제
ch07ex15_PointOperator.cpp
#include <iostream>
#include <string>
using namespace std;
class Point
{
friend Point operator+(int num, const Point& other);
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
~Point() {}
string getPoint() const
{
return "(" + to_string(this->x) + ", " + to_string(this->y) + ")";
}
Point operator+(Point& other)
{
return Point(this->x + other.x, this->y + other.y);
}
Point operator+=(const Point& other)
{
this->x += other.x;
this->y += other.y;
return *this;
}
Point& operator++()
{
this->x++;
this->y++;
return *this;
}
Point operator++(int)
{
return Point(this->x++, this->y++);
}
Point operator+(int a) const
{
return Point(this->x + a, this->y + a);
}
bool operator==(const Point& other)
{
return (this->x == other.x && this->y == other.y);
}
friend ostream& operator<<(ostream& os, const Point& p)
{
os << "(" << p.x << ", " << p.y << ")";
return os;
}
friend istream& operator>>(istream& is, Point& p)
{
is >> p.x >> p.y;
return is;
}
private:
int x;
int y;
static int pointCount;
};
Point operator+(int num, const Point& other)
{
return Point(other.x + num, other.y + num);
}
int Point::pointCount = 0;
int main()
{
Point p1(1, 2);
Point p2(2, 3);
Point p3;
cout << "p1 == p2: " << (p1 == p2) << endl;
p3 = p1 + p2;
cout << "p1: " << p1.getPoint() << endl;
cout << "p2: " << p2.getPoint() << endl;
cout << "p3: " << p3.getPoint() << endl;
cout << "p1 + p3: " << (p1 + p3).getPoint() << endl;
p1 += p2;
cout << "p1: " << p1.getPoint() << endl;
p1 += p2 += p3;
cout << "p1: " << p1.getPoint() << endl;
cout << "p2: " << p2.getPoint() << endl;
++p1;
cout << "p1: " << p1.getPoint() << endl;
++(++p1);
cout << "p1: " << p1.getPoint() << endl;
Point result; // 생성자 호출
result = p2++; // p2.operator++(), result.operator=(p2) 호출
cout << "result: " << result.getPoint() << endl;
cout << "p2: " << p2.getPoint() << endl;
Point p4 = p1 + 10; // 복사 생성자 호출
cout << "p4: " << p4.getPoint() << endl;
Point p5 = 10 + p1; // 좌측 피연산자가 기본 타입인 경우 메서드 호출 불가
cout << "p5: " << p5.getPoint() << endl;
cout << endl << endl;
Point p6;
cout << "좌표 x, y: ";
cin >> p6;
cout << "p6: " << p6 << endl;
return 0;
}Last updated