[ C++ ] 프렌드함수 || 연산자 중복 || 프렌드함수 예제, 연산자 중복 예제

2021. 5. 11. 12:30·Archive/Develop
728x90
반응형

 

프렌드함수

 

: 클래스의 멤버 함수가 아닌 외부함수

 

: 전역 함수

 

: friend 키워드로 클래스 내에 선언된 함수

 

: 클래스의 멤버로 선언하기에는 무리가 있는, 클래스의 모든 멤버를 자유롭게 접근할 수 있는

  일부 외부 함수를 작성 할 때 필요하다.

 

 

클래스의 모든 멤버를 접근할 수 있는 권한이 부여된다.

 

 

 

 

프렌드 함수가 되는 세가지

 

: 전역함수 - 클래스 외부에 선언된 전역 함수

 

: 다른 클래스의 멤버 함수 - 다른 클래스의 특정 멤버함수

 

: 다른 클래스 전체 - 클래스의 모든 멤버 함수

 

 

 

 

1. 외부함수 equals() 를 Rect 클래스의 프렌드로 선언하는 것

 

class Rect{
	friend bool equals(Rect r, Rect s);
}

 

 

 

#include <iostream>
using namespace std;

class Rect;
bool equals(Rect r, Rect s);

class Rect {
	int width, height;
public:
	Rect(int width, int height) {
		this->width = width; 
		this->height = height;
	}
	friend bool equals(Rect r, Rect s);
};

bool equals(Rect r, Rect s) {
	if (r.width == s.width && r.height == s.height) return true;
	else return false;

}

int main() {
	Rect a(3, 4), b(4, 5);
	if (equals(a, b)) cout << "equal" << endl;
	else cout << "not equal" << endl;
	
}

 

 

 

 

 

2. RectManager 클래스의 equals 멤버 함수를 Rect 클래스의 프렌드로 선언하는 것

 

class Rect{
	friend bool RectManager::equals(Rect r, Rect s);
}

 

 

#include <iostream>
using namespace std;

class Rect;

class RectManager {
public:
	bool equals(Rect r, Rect s);
};

class Rect {
	int width, height;
public:
	Rect(int width, int height) {
		this->width = width; 
		this->height = height;
	}
	friend bool RectManager::equals(Rect r, Rect s);
};

bool RectManager::equals(Rect r, Rect s) {
	if (r.width == s.width && r.height == s.height) return true;
	else return false;

}

int main() {
	Rect a(3, 4), b(4, 5);
	RectManager man;
	if (man.equals(a, b)) cout << "equal" << endl;
	else cout << "not equal" << endl;
	
}

 

 

 

 

 

3. RectManager 클래스 전체를 Rect 클래스의 프렌드로 선언하는 것

 

class Rect{
	friend RectManager;
}

 

 

#include <iostream>
using namespace std;

class Rect;
class RectManager {
public:
	bool equals(Rect r, Rect s);
	void copy(Rect& destm ,Rect& src);
};
class Rect {
	int width, height;
public:
	Rect(int width, int height) {
		this->width = width; 
		this->height = height;
	}

	friend RectManager;
};

bool RectManager::equals(Rect r, Rect s) {
	if (r.width == s.width && r.height == s.height) return true;
	else return false;

}

void RectManager::copy(Rect& dest, Rect& src) {
	dest.width = src.width; dest.height = src.height;
}

int main() {
	Rect a(3, 4), b(4, 5);
	RectManager man;
	man.copy(b, a);
	if (man.equals(a, b)) cout << "equal" << endl;
	else cout << "not equal" << endl;
	
}

 

 

 

 

 

연산자 중복

 

 

연산자를 재정의 해 사용할 수 있는 것이다.

 

 

: c++ 에 본래 있는 연산자만 중복 가능하다.

 

: 피 연산자 타입이 다른 새로운 연산 정의

 

: 연산자는 함수형태로 구현한다. -> 연산자 함수

 

: 반드시 클래스와 관계를 가진다.

 

: 피연산자의 개수를 바꿀 수 없다

 

: 연산의 우선 순위 변경은 안된다.

 

: 모든 연산자가 중복가능하지 않다.

 

: 예를 들어, . 이나 :: , ?: (3항 연산자) 등이 중복 불가능하다.

 

 

연산자 함수 구현방법 2가지

 

 

연산자 함수는

 

1. 클래스의 멤버함수로 구현

2. 외부함수로 구현하고 클래스에 프렌드 함수로 선언

 

 

하는 두가지의 방법으로 구현 가능하다.

 

 

함수의 형식은 아래와 같다.

 

리턴타입 operator연산자(매개변수리스트);

 

 

 

 

연산자 중복 예제 1 

 

 

#include <iostream>
using namespace std;


class Test {
	int x=0, y=0;
public:
	Test(){	}
	Test(int x, int y) {
		this->x = x;
		this->y = y;
	}
	~Test(){}
	void show() {
		cout << "x = " << x << ", y = " << y << endl;
	}
	//Test operator+(int k) {
	//	x += k;
	//	y += k;
	//}
	//Test operator-(int k) {
	//	x -= k;
	//	y -= k;
	//}
	Test operator+(int k) {
		x = this->x + k;
		y = this->y + k;
		return *this;
	}
	Test operator-(int k) {
		x = this->x - k;
		y = this->y - k;
		return *this;
	}
	Test operator+(Test op) {
		Test tmp;
		tmp.x = this->x+op.x;
		tmp.y = this->y+op.y;

		return tmp;
	}
	Test operator-(Test op) {
		Test tmp;
		tmp.x = this->x - op.x;
		tmp.y = this->y - op.y;

		return tmp;
	}
};

int main() {
	Test a(5, 3), b(6, 7),c(5,3), t,s;
	a.show();
	b.show();
	t.show();
	cout << "==============" << endl;
	a.operator+(5);
	a.show(); // x = 10, y = 8
	b.operator-(3);
	b.show(); // x = 3, y = 4
	t = a.operator+(b); // a.operator+(b)
	t.show();
	s = b - c;
	s.show();
}

 

 

 

 

 

 

연산자 중복 예제2

 

 

class Color {
	int r=0, g=0, b=0;
public:
	Color(){}
	Color(int r, int g, int b) {
		this->r = r;
		this->g = g;
		this->b = b;
	}
	Color operator+(Color a) {
		Color tmp;
		tmp.r = this->r + a.r;
		tmp.g = this->g + a.g;
		tmp.b = this->b + a.b;

		return tmp;
	}

	bool operator==(Color a) {
		if (this->r == a.r && this->g == a.g && this->b == a.b) {
			return true;
		}
		return false;
		
	}

	friend Color operator+(int n, Color a);

	void show() {
		cout << this->r << " " << this->g << " " << this->b << endl;
	}
};

Color operator+(int n, Color a) {
	a.r += n;
	a.g += n;
	a.b += n;

	return a;
}

int main() {
	Color red(255, 0, 0), blue(0, 0, 255),green(0,250,10),c;
	c = red + blue;
	Color fuchsia(255, 0, 255);
	if (c == fuchsia) {
		cout << "보~라" << endl;
	}
	else {
		cout << "보~라 아님" << endl;
	}
	c = 5 + green;
	c.show();

}

 

 

 

 

 

 

 

728x90
반응형

'Archive > Develop' 카테고리의 다른 글

[ C++ ] 가상함수와 추상클래스  (0) 2021.05.26
[ C++ ] 상속의 개념 | 상속 예제  (0) 2021.05.18
[ Oracle ] 프로시저와 sql*plus 예제 (프로시저 호출하는 방법)  (0) 2021.05.10
[ C++ ] 함수 중복(Function Overloading)  (0) 2021.05.04
[ Oracle ] Oracle PL/SQL 화면출력 & 간단 예제  (0) 2021.05.03
'Archive/Develop' 카테고리의 다른 글
  • [ C++ ] 가상함수와 추상클래스
  • [ C++ ] 상속의 개념 | 상속 예제
  • [ Oracle ] 프로시저와 sql*plus 예제 (프로시저 호출하는 방법)
  • [ C++ ] 함수 중복(Function Overloading)
코뮤(commu)
코뮤(commu)
코딩으로 커뮤니케이션하는 코뮤입니다 😎
  • 코뮤(commu)
    코뮤(COMMU)
    코뮤(commu)
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Archive
        • Hacking
        • Develop
        • ETC
      • Algorithm
      • DB&Infra
      • ETC
      • Node
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • IT지식보따리
    • IT가 맛있다
    • IT 천재
  • 공지사항

    • 배고픕니다
  • 인기 글

  • 태그

    파이썬
    oracle db
    C++
    파이썬 알고리즘
    파이썬 기초
    자바스크립트 API
    비박스
    자바스크립트 객체
    javascript
    백준 파이썬
    장고
    카카오 100일 프로젝트
    docker
    백준
    파이썬 백준
    Python
    보안뉴스
    Django
    Git
    코드업 기초
    Oracle
    파이썬 기초 문제
    파이썬 문제
    Codeup
    백준 문제풀이
    백준 풀이
    자바스크립트
    오라클
    코드업
    코드업 파이썬 기초 100제
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
코뮤(commu)
[ C++ ] 프렌드함수 || 연산자 중복 || 프렌드함수 예제, 연산자 중복 예제
상단으로

티스토리툴바