2008. 9. 2. 15:57

c++ operator_overloading

#include<iostream>

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

//////////////////////////////////////////////
class MyClass
{
public:
 MyClass operator+(MyClass &my);// 덧셈 함수
 MyClass(double _a=0, double _b=0);//디폴트 파라미터를 갖는 생성자( 인수없이 객체 생성시

에 필요)
 
 void Out();//출력 함수
private:
 int a,b;
};


//////////////////////////////////////////////
MyClass::MyClass(double _a, double _b):a(_a),b(_b){}

MyClass MyClass::operator+(MyClass &my)
{
 MyClass temp;
 
 temp.a = a+my.a;
 temp.b = b+my.b;

 return temp;
}
void MyClass::Out()
{
 cout<<a<<" " <<b<<endl;
}

int main()
{
 MyClass m1(1.1,2.2);
 MyClass m2(1.1,2.2);
 MyClass m3;

// m3= m1.Add(m2);
 m3= m1+m2;//내부적으로 변환된 코드   ---> m1.operator+(m2)
 //좌측 피연산자 : 호출객체 , 함수 이름: operator[연산자], 우측 피연산자 : 인수
 m1.Out();
 m2.Out();
 m3.Out();

 return 0;
}



#include<iostream>

using std::cout;
using std::endl;
///////////////////////////////////////////
class Point
{
public:
 //생성자
 Point(int _a=0,int _b=0);
 //연산자 오버로딩 [==]
 bool operator==(Point &po);
 //연산자 오버로딩 [+]
 Point operator+(Point &pl);
 //연산자 오버로딩 [+=]
 Point operator+=(Point &pp);

 void show()const;
private:
 int a,b;
};

///////////////////////////////////////////
Point::Point(int _a,int _b):a(_a),b(_b){}
bool Point::operator==(Point &po)
{
 if(a==po.a&&b==po.b)
  return true;
 else
  return false;
}
Point Point::operator+(Point &pl)
{
 Point temp;
 temp.a=a+pl.a;
 temp.b=b+pl.b;

 return temp;
}
void Point::show()const
{
 cout<<"a : "<<a<<endl;
 cout<<"b : "<<b<<endl;
}
Point Point::operator+=(Point &pp)
{

 a+=pp.a;
 b+=pp.b;
 return *this;
}
int main()
{

 Point p1(2,1);
 Point p2(2,1);

 if(p1==p2)
   cout<<"같다"<<endl;
 else
   cout<<"다르다"<<endl;
 
 Point p3;
 p3=p1+p2;

 p3.show();

 p2+=p3;
 p2.show();

 p1+=p2+=p3;
 p1.show();


 return 0;
}