C++ : 연산자 오버로딩(1) - 기본

참고 : 열혈강의 C++ 프로그래밍 책


#include <iostream>

using namespace std;

class OperPoint
{
private:
 int xpos, ypos;

public:
 OperPoint(int x = 0, int y = 0) : xpos(x), ypos(y)
 { }

 void ShowPosition() const
 {
  cout << '[' << xpos << ", " << ypos << ']' << endl;
 }

 // operator 키워드와 + 연산자를 묶어서 함수의 이름을 정의하면
 // 함숨 이름 뿐만 아니라 연산자를 이용한 함수의 호출도 허용
 // const를 선언하는 것은 피연산자의 값을 변경하기 않기 때문이다
 OperPoint operator+(const OperPoint &ref)
 {
  OperPoint pos(xpos + ref.xpos, ypos + ref.ypos);
  return pos;
 }
};

// 테스트 함수
void Operator1()
{
 OperPoint pos1(3, 4);
 OperPoint pos2(10, 20);
 OperPoint pos3 = pos1+pos2;

 pos1.ShowPosition();
 pos2.ShowPosition();
 pos3.ShowPosition();
}

댓글

이 블로그의 인기 게시물

C++ : Class로 만든 DLL Export 및 Import

VMware 환경에서 우분투로 안드로이드 환경 구축하기(1)