#7 [c++]참조, 객체의 복사, 다형성

정상준·2022년 10월 27일
0

c++

목록 보기
4/25

1. 참조에 의한 호출

1) 함수의 매개 변수를 참조 타입으로 선언

  • 형식
    1) 변수타입 함수명(변수타입 &변수명)
    2) void func(int &val)

예시)

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

/* 출력
   9 2
*/

void swap(int& a, int& b) {
	int tmp = a;
	a = b;
	b = tmp;
}

int main() {
	int m = 2, n = 9;
	swap(m, n);
	cout << m << " " << n;
}

2) 참조의 호출이 필요한 경우

  • 반환되는 데이터에 여러 종류인 경우

3) 참조를 이용한 반환

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

/* 
출력
평균은 2
매개 변수 오류
*/

bool average(int a[], int size, int& avg) {
	if (size <= 0) {
		return false;
	}
	int sum = 0;
	for (int i = 0; i < size; i++) {
		sum += a[i];
	}
	avg = sum / size;
	return true;
}

int main() {
	int x[] = {0,1,2,3,4,5};
	int avg;
	if (average(x, 6, avg)) {
		cout << "평균은 " << avg << endl;
	}
	else
	{
		cout << "매개 변수 오류" << endl;
	}

	if (average(x, -2, avg)) {
		cout << "평균은 " << avg << endl;
	}
	else
	{
		cout << "매개 변수 오류" << endl;
	}
}

4) 참조에 의한 객체 전달

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

/* 
출력
생성자 실행 radius = 30
31
소멸자 실행 radius = 31
*/

class Circle {
private:
	int radius;
public:
	Circle() :Circle(1) {}
	Circle(int radius) {
		this->radius = radius;
		cout << "생성자 실행 radius = " << radius << endl;
	}
	~Circle() {
		cout << "소멸자 실행 radius = " << radius << endl;
	}
	double getArea() { return 3.14 * radius * radius; }
	int getRadius() { return radius; }
	void setRadius(int radius) { this->radius = radius; }
};

void increaseCircle(Circle& c) {
	int r = c.getRadius();
	c.setRadius(r + 1);
}

int main() {
	Circle ring(30);
	increaseCircle(ring);
	cout << ring.getRadius() << endl;
}

5) 참조 리턴

  • 함수는 값 외에 참조 리턴 가능
  • 참조 리턴
    • 변수 등과 같이 현존하는 공간에 대한 참조 리턴
#include <iostream>
#include <string>
using namespace std;

/* 
출력
	Mike
	Sike
	Site
*/

char& find(char s[], int index) {
	return s[index];
}

int main() {
	char name[] = "Mike";
	cout << name << endl;
	find(name, 0) = 'S';
	cout << name << endl;
	char& ref = find(name, 2);
	ref = 't';
	cout << name << endl;
}

2. 객체의 복사

1) 얕은 복사 : 포인터만 복사

2) 깊은 복사 : 포인터의 메모리도 복사

3) 복사 생성자

특징

  • 객체의 복사 생성시 호출되는 생성자
  • 한 클래스에 한 개만 선언 가능
  • 클래스에 대한 참조 매개 변수를 갖는 모양
#include <iostream>
#include <string>
using namespace std;

/* 
출력
	복사 생성자 실행 radius = 30
	원본의 면적 = 2826
	사본의 면적 = 2826
*/

class Circle {
private:
	int radius;
public:
	Circle(const Circle& c);
	Circle() :Circle(1) {}
	Circle(int radius) {
		this->radius = radius;
	}
	double getArea() { return 3.14 * radius * radius; }
};

Circle::Circle(const Circle& c) {
	this->radius = c.radius;
	cout << "복사 생성자 실행 radius = " << radius << endl;
}

int main() {
	Circle src(30);
	Circle dest(src);
	cout << "원본의 면적 = " << src.getArea() << endl;
	cout << "사본의 면적 = " << dest.getArea() << endl;
}

3. 다형성

1) 함수 중복

  • 동일한 이름의 함수 사용 가능
  • 중복된 이름의 함수지만 매개 변수의 타입이나 개수가 달라야함
  • 리턴 타입은 함수 중복과 관계 없음
  • 동일한 이름의 함수를 사용하기 때문에 함수의 이름을 구분할 필요가 없는 장점이 있음

2) 오버로딩

  • 함수 간에 함수 중복

3) 오버라이딩

  • 상속 받은 객체간에 함수 중복

함수 중복의 예)

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

/* 
출력
	두 수 중 큰 수는 7
	배열에서 가장 큰 수는 10
*/

int compare(int a, int b) {
	if (a > b) return a;
	else return b;
}

int compare(int a[], int size) {
	int result = a[0];
	for (int i = 1; i < size; i++) {
		if (result < a[i]) {
			result = a[i];
		}

		return result;
	}
}

int main() {
	int array[5] = { 2,10,7,8,5 };
	cout << "두 수 중 큰 수는 " << compare(5, 7) << endl;
	cout << "배열에서 가장 큰 수는 " << compare(array, 5) << endl;
}

4. 디폴트 매개 변수

1) 특징

  • 매개 변수의 값을 전달하지 않은 경우 호출된 함수에서 갖게되는 디폴트 값
  • 제약사항
    • 일반 매개 변수 앞에 선언될 수 없음
      • void sum(int a = 0, int b, int c); //컴파일 오류
      • void sum(int a, int b = 0, int c); //컴파일 오류
    • 일반 매개 변수 뒤에 선언되어야 하는 규칙
      • void sum(int a, int b, int c = 0);
      • void sum(int a, int b = 0, int c = 0);

예시.

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

/* 
출력
	***
	*****
	5
	10 Hellow
*/

void drawStar(int a = 3) {
	for (int i = 0; i < a; i++) 
		cout << "*";
		cout << endl;
}

void msg(int id, string text = "") {
	cout << id << ' ' << text << endl;
}

int main() {
	drawStar();
	drawStar(5);
	msg(5);
	msg(10, "Hellow");
}
profile
안드로이드개발자

0개의 댓글