//전역함수에 대해서
#include<iostream>usingnamespacestd;classRect{intwidth,height;public:Rect(intwidth,intheight){this->width=width;this->height=height;}friendboolequals(Rect&r,Rect&s);// friend 키워드 사용
};boolequals(Rect&r,Rect&s){if(r.width==s.width&&r.height==s.height)returntrue;elsereturnfalse;}intmain(void){Recta(3,4),b(4,5);if(equals(a,b))cout<<"equal"<<endl;elsecout<<"not equal"<<endl;return0;}
다른 클래스의 멤버함수
다른 클래스의 특정 멤버 함수 friend bool RectManager::equals(Rect& r, Rect& s);
//다른 클래스의 멤버함수에 대해서
#include<iostream>usingnamespacestd;classRect;classRectManager{public:boolequals(Rect&r,Rect&s);//선언과 정리를 분리해서 구현
};classRect{friendboolRectManager::equals(Rect&r,Rect&s);// friend 키워드 사용
intwidth,height;public:Rect(intwidth,intheight){this->width=width;this->height=height;}};boolRectManager::equals(Rect&r,Rect&s){if(r.width==s.width&&r.height==s.height)returntrue;elsereturnfalse;}intmain(void){Recta(3,4),b(4,5);RectManagerman;if(man.equals(a,b))cout<<"equal"<<endl;elsecout<<"not equal"<<endl;return0;}
//다른 클래스 전체에 대해
#include<iostream>usingnamespacestd;classRect;classRectManager{public:boolequals(Rect&r,Rect&s);//선언과 정리를 분리해서 구현
voidcopy(Rect&r,Rect&s);};classRect{friendclassRectManager;// friend 키워드 사용
intwidth,height;public:Rect(intwidth,intheight){this->width=width;this->height=height;}};boolRectManager::equals(Rect&r,Rect&s){if(r.width==s.width&&r.height==s.height)returntrue;elsereturnfalse;}voidRectManager::copy(Rect&r,Rect&s){//write codes
}intmain(void){Recta(3,4),b(4,5);RectManagerman;if(man.equals(a,b))cout<<"equal"<<endl;elsecout<<"not equal"<<endl;return0;}
연산자 중복(연산자 오버로딩)
본래부터 있던 연산자의 의미를 재정의(함수 구현)
멤버함수로 구현하는 방법과 전역함수로 구현하는 방법이 있다.
#include<iostream>usingnamespacestd;classPoint{intxpos,ypos;public:Point(intxpos=0,intypos=0){this->xpos=xpos;this->ypos=ypos;}voidshowPos(){cout<<xpos<<' '<<ypos<<endl;}//지역 변수에서 생성된 객체이기 때문에 레퍼런스 사용 불가.
Pointoperator+(Point&p2){Pointtmp;tmp.xpos=xpos+p2.xpos;tmp.ypos=ypos+=p2.ypos;returntmp;}};intmain(void){Pointpos1(10,20),pos2(20,30),pos3;pos3=pos1+pos2;pos1.showPos();pos2.showPos();pos3.showPos();return0;}
#include<iostream>usingnamespacestd;classMatrix{intarr[4];public:Matrix(inta=0,intb=0,intc=0,intd=0){this->arr[0]=a;this->arr[1]=b;this->arr[2]=c;this->arr[3]=d;}voidshow(){cout<<"Matrix = < "<<arr[0]<<' '<<arr[1]<<' '<<arr[2]<<' '<<arr[3]<<" >"<<endl;}Matrixoperator+(Matrix&m){Matrixtmp;for(inti=0;i<4;i++)tmp.arr[i]=arr[i]+m.arr[i];returntmp;}Matrix&operator+=(Matrix&m){for(inti=0;i<4;i++)arr[i]+=m.arr[i];return*this;}booloperator==(Matrix&m){for(inti=0;i<4;i++)if(arr[i]!=m.arr[i])returnfalse;returntrue;}};intmain(void){Matrixa(1,2,3,4),b(2,3,4,5),c;c=a+b;a+=b;a.show();b.show();c.show();if(a==c)cout<<"a and c are the same"<<endl;return0;}