#8 [c++]함수 중복, static, friend, 연산자 중복

정상준·2022년 10월 27일
0

c++

목록 보기
1/25

📝 함수 중복의 간소화

Circle() { radius = 1;}
Circle(int r=1) {radius = r;}
구분 가능
Circle(int r) {radius = 1;}
Circle(int r = 1) {radius = r;}
함수의 중복은 매개변수 갯수와 타입으로 구분하는데 위와 같은경우 구분 불가

📝 함수 중복의 모호성

📍 가능
double square(double a){
	return a*a;
}
int main(){ //형변환
	cout << square(3)
}
📍 변수의 형 변환으로 인한 함수 중복의 모호성
double square(double a){
	return a*a;
}
float square(float a){
	return a*a;
}
int main(){ //형변환
	cout << square(3)
}
📍 디폴트 매개 변수로 인한 함수 중복의 모호성
void msg(int id){
	cout<<id<<endl;
}
void msg(int id, string s=""){
	cout<<id<<":"<<s<endl;
}
int main(){ //형변환
	msg(5)
}
📍 참조 매개 변수로 인한 함수 중복의 모호성
int add(int a, int b){return a+b;}
int add(int a, int &b) {return b = b + a}
int main(){
	int a = 10, b = 20;
    cout<<add(a,b);
}

📝static 멤버

✏️ static

  • 변수의 선언
  • 프로그램이 시작될 때 생성되고 종료될 때 소멸

✏️ 클래스의 static 멤버

  • static 멤버
    -- 프로그램이 시작할 때 생성
    -- 클래스 당 하나만 생성(모든 객체가 하나의 멤버를 공유)
  • 선언
    -- static 변수타입 변수명;
    -- static int totalAccount;
  • 초기화
    -- static 멤버 변수에 대한 클래스 외부 초기화 필요함
    -- int Bank::totalAccount = 0;

/* 
출력
	100 350
	400 400
*/

class Person {
public:
	int money; //개인 소유의 돈
	void addMoney(int money) {
		this->money += money;
	}
	static int sharedMoney; //공금
	static void addShared(int n) { sharedMoney += n; }
};

int Person::sharedMoney = 10;

int main() {
	Person kim;
	kim.money = 100;
	kim.sharedMoney = 200;
	Person lee;
	lee.money = 150;
	lee.addMoney(200);
	lee.addShared(200);
	cout << kim.money << ' ' << lee.money << endl;
	cout << kim.sharedMoney << ' ' << lee.sharedMoney << endl;
}

📝 static 활용

✏️ 객체 사이에 공유

  • static 멤버를 선언한 클래스로부터 생성된 모든 객체들 공유

✏️ 제약사항

  • static 멤버가 public으로 선언된 경우
    -- 클래스의 캡슐화를 유지할 수 없음
    -- 외부에서 static으로 선언된 멤버 접근 가능
  • static 멤버 함수의 접근
    -- static 멤버 함수는 non-static 멤버 접근 불가
    -- non-static 함수는 static 멤버 접근 가능

#include <iostream>
#include <string>
using namespace std;

/* 
출력
	1
	20
	-5
*/

class Math {
public:
	static int abs(int a) { return a > 0 ? a : -a; }
	static int max(int a, int b) { return a > b ? a : b; }
	static int min(int a, int b) { return a > b ? b : a; }
};

int main() {
	cout << Math::abs(-1) << endl;
	cout << Math::max(10, 20) << endl;
	cout << Math::min(-5, 5) << endl;
}

#include <iostream>
#include <string>
using namespace std;

/* 
생성된 원의 갯수= 10
생성된 원의 갯수= 0
생성된 원의 갯수= 1
*/

class Circle {
private:
	static int numOfCircle;
	int radius;
public:
	Circle(int r = 1);
	~Circle() { numOfCircle--;}
	static int getNumofCircle() { return numOfCircle; }
};
Circle::Circle(int r) {
	radius = r;
	numOfCircle++;
}
int Circle::numOfCircle = 0;


int main() {
	Circle* p = new Circle[10];
	cout << "생성된 원의 갯수= " << Circle::getNumofCircle() << endl;
	delete[]p;
	cout << "생성된 원의 갯수= " << Circle::getNumofCircle() << endl;
	Circle a;
	cout << "생성된 원의 갯수= " << Circle::getNumofCircle() << endl;
}

📝 friend

✏️ 프랜드 함수

  • 클래스의 멤버가 아닌 외부 함수
  • 클래스의 모든 멤버 접근 할 수 있는 권한
  • 종류
    -- 전역함수 : 클래스 외부에 선언된 전역함수
    -- 다른 클래스의 멤버 함수
    -- 다른 클래스의 모든 멤버 함수
외부 전역함수
#include <iostream>
#include <string>
using namespace std;

/* 
not equal
*/

class Rectangle;
bool equals(Rectangle r, Rectangle s);
class Rectangle {
	int width, height;
public:
	Rectangle(int w, int h) {
		width = w; 
		height = h;
	}
	friend bool equals(Rectangle r, Rectangle s);
};

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

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

다른 클래스의 멤버함수
#include <iostream>
#include <string>
using namespace std;

/* 
not equal
*/

class Rectangle;
class RectangleManager {
public:
	bool equals(Rectangle r, Rectangle s);
};
class Rectangle {
	int width, height;
public:
	Rectangle(int w, int h) {
		width = w; 
		height = h;
	}
	friend bool RectangleManager::equals(Rectangle r, Rectangle s);
};

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

int main() {
	Rectangle a(1, 2), b(3, 4);
	RectangleManager manage;
	if (manage.equals(a, b)) {
		cout << "equal" << endl;
	}
	else{
		cout << "not equal" << endl;
	}
}

📝 연산자 중복

✏️ 일반적인 연산자의 대상

  • 숫자만 가능
  • 문자열 안됨
  • 객체 안됨

✏️ C++의 연산자 중복 대상

  • 객체 가능
  • 문자열 가능
  • 추가적인 연산자 중복 정의 가능

✏️ 구현 방법

  • 클래스의 멤버 함수로 구현하는 방법
  • 외부 함수로 구현하고 friend 함수로 선언

이항 연산자 + 중복
#include <iostream>
#include <string>
using namespace std;

/* 
radius = 3;price5
radius = 4;price6
radius = 7;price11
*/

class Circle {
	int radius;
	int price;
public:
	Circle(int r = 0, int p = 0) {
		radius = r;
		price = p;
	}
	void show();
	Circle operator+(Circle op2);
};
void Circle::show() {
	cout << "radius = " << radius << ";" << "price" << price << endl;;
}

Circle Circle::operator+(Circle op2) {
	Circle tmp;
	tmp.radius = this->radius + op2.radius;
	tmp.price = this->price + op2.price;
	return tmp;
}

int main() {
	Circle a(3, 5), b(4, 6), c;
	c = a + b;
	a.show();
	b.show();
	c.show();
}

다른 타입과 +연산자 중복
#include <iostream>
#include <string>
using namespace std;

/* 
radius = 3;price5
radius = 0;price0
radius = 3;price5
radius = 5;price7
*/

class Circle {
	int radius;
	int price;
public:
	Circle(int r = 0, int p = 0) {
		radius = r;
		price = p;
	}
	void show();
	Circle operator+(int op2);
};
void Circle::show() {
	cout << "radius = " << radius << ";" << "price" << price << endl;;
}

Circle Circle::operator+(int op2) {
	Circle tmp;
	tmp.radius = this->radius + op2;
	tmp.price = this->price + op2;
	return tmp;
}

int main() {
	Circle a(3, 5), b;
	a.show();
	b.show();
	b = a + 2;
	a.show();
	b.show();
}
profile
안드로이드개발자

0개의 댓글