말 그대로 연산자를 오버로딩 하는 것이다.
형식은 다음과 같다.
Point operator+(const Point &ref)
{
Point pos(xpos+ref.xpos, ypos+ref.ypos);
return pos;
}
연산자 오버로딩은 멤버 함수나 전역 함수로 만들 수 있다.
Point operator+(const Point& ref1, const Point& ref2)
{
Point ref (ref1.x + ref2.x, ref1.y+ref2.y );
return ref;
}
멤버 함수와 전역함수로 동시에 오버로딩이 되어 있으면 멤버함수의 우선순위가 더 높다.
만약 private인 멤버변수에 전역 함수로 접근하고 싶다면, freind 선언이 필요하다.
class Point
{
...
friend Point operator+(const Point& ref1, const Point& ref2); // 변수 이름을 빼도 동작한다.
};
Point operator+(const Point& ref1, const Point& ref2)
{
Point ref (ref1.x + ref2.x, ref1.y+ref2.y );
return ref;
}
복사 생성자는 객체를 새로 생성할 때 호출된다.
상속 구조에서 부모 클래스의 대입연산자는 필요 없는지 살펴야 한다.
멤버 이니셜라이저로 멤버 객체를 초기화 할때 복사생성자가 호출된다.
정의된 부분으로 대입연산 한다면 생성자와 대입연산자가 호출된다.
전위 증가(감소) Point& operator++()
후위 증가(감소) const Point operator++(int)
Point operator=(const Point& ref)
c++에서 기본 타입의 후위 연산인 경우 const 형태를 반환한다.
오버로딩이 불가능한 연산자 | 멤버 함수로 오버로딩 해야하는 연산자 |
---|---|
. | = |
.* | ( ) |
:: | [ ] |
?: | -> |
sizeof | |
typeid | |
형 변환 연산자 4 |
전역 변수에 선언된 static
함수 내에 선언된 static
정적 멤버 변수
정적 멤버 함수