2008. 9. 3. 15:50

c++ 연산자 중복오버로딩 , friend 함수


#include<iostream>

using std::cout;
using std::cin;
using std::endl;

//////////////////////////////////////////////////////////////////////
class My
{
 // 프렌드 함수 - 클래스와 전역 함수가 밀접한 관계를 갖는 경우 선언
 // 전역함수는 클래스의 모든 멤버를 자유롭게 접근
 friend My operator+(int n, My &my); //프렌드 함수
public:
 My(double _a=0, double _b=0);
 My operator+(int c);
 void Out();
private:
 double a,b;

};

My::My(double _a, double _b):a(_a),b(_b)
{ }
My My::operator+(int c)
{
 My temp ;
 temp.a=a+c;
 temp.b=b+c;
 
 return temp;
}
void My::Out()
{
 cout<<"a="<<a<<" "<<"b="<<b<<endl;
}

//////////////////////////////////////////
My operator+(int n, My &my)
{
 My temp;
 temp.a = n + my.a;
 temp.b = n + my.b;
 return temp;
}
int main()
{
 My m1(1.1,2.2);

 My m2;
 m2 = m1+10; // m1.operator+(10);

 m1.Out();
 m2.Out();
 
 My m3;
 //좌측 피연산자가 기본자료형이 되는 경우 클래스의 멤버 함수 호출 불가
 m3 = 10+m1; // m1.operator+(10);

 m3.Out();
 
 return 0;

}
A1 + A2
  1. 멤버 함수 : 좌측 호출 객체 + 우측 인수  -> A1.operator+(A2)
  2. 전역 함수 : 좌측 인수 + 우측 (인수)객체    ->  operator+(a1+a2);
++A
  1. 멤버 함수 : 호출 객체
    a.operator++();
  2. 전역 함수 : 인수
    operator++(a);

#include<iostream>

using std::cout;
using std::cin;
using std::endl;

/////////////////////////////////////////클래스 선언
class Point
{
 //프렌드 함수 선언
 friend Point& operator--(Point &pbar);
public:
 Point(int _a, int _b);
 Point& operator++();
 void Show();
private:
 int a, b;
};
///////////////////////////////////////외부 정의
Point::Point(int _a, int _b):a(_a),b(_b)
{
}
//Point&    레퍼런스로 리턴 시 복사본은 생성되지 않는다.( 참고 :Point* 주소로 받겠다.)
Point& Point::operator++()
{
 ++a;
 ++b;
 return *this; // this (주소) --> *this (주소가 가리키는 값)
}
///             this 호출한 객체의 주소저장되어있다!!!!!!!!!!!
void Point::Show()
{
 cout<<"a = "<<a<<" " <<" b = "<<b<<endl;
}
/////////////////////////////////////////전역 함수
Point& operator--(Point &pbar)
{
 --pbar.a;
 --pbar.b;
 return pbar;
}

int main()
{
 Point p(5,6);
 
 ++++p;
 p.Show(); //p.operator++();

 ------p;
 p.Show(); //operator--(p);
 
 return 0;

}