함수 오버로딩

이영준·2022년 3월 30일
0
post-thumbnail

🔑함수 오버로딩

• 프로그래머는 입력 매개변수가 다른 한 동일한 이름으로 여러 함수를 만들 수 있습니다.

ex)

#include <iostream>
using namespace std;

int Add(int arg1, int arg2) {
	cout << "int Add" << endl;
	return arg1 + arg2;
}

double Add(double arg1, double arg2) {
	cout << "double Add" << endl;
	return arg1 + arg2;
}

double Add(int arg1, double arg2) {
	cout << "double Int Add" << endl;
	return arg1 + arg2;
}

void main() {
	cout << Add(1, 1) << endl; 
	cout << Add(1.0 , 1.0) << endl;
	cout << Add(1 , 1.0) << endl;
}

함수 오버로딩 퀴즈

#include <iostream>

using namespace std;
class Triangle {
	int width;
	int height;

public:
	Triangle() {}
	Triangle(int argWidth, int argHeight) : width(argWidth), height(argHeight) {}
	int GetWidth() {
		return width;
	}
	int GetHeight() {
		return height;
	}
};

class Square{

	int width;

public:
	Square() {}
	Square(int argSide) : width(argSide) {}
	int GetWidth() {
		return width;
	}
};

class Circle {

	int radius;

public:
	Circle() {}
	Circle(int argRadius) : radius(argRadius) {}
	int GetRadius() {
		return radius;
	}
};

int Calculate(Triangle a) {
	return a.GetWidth()* a.GetHeight() / 2;
}

int Calculate(Square a) {
	return pow(a.GetWidth(), 2);
}

double Calculate(Circle a) {
	return 3.14 * pow(a.GetRadius(),2);
}

int main() {
	Triangle tri(5, 2);
	Square square(5);
	Circle circle(5);
	cout << "Area of Triangle = " << Calculate(tri) << "\n";
	cout << "Area of Square = " << Calculate(square) << "\n";
	cout << "Area of Circle = " << Calculate(circle) << "\n";
}

🔑생성자 오버로딩

• 함수 오버로드와 유사한 방법으로 생성자를 오버로드할 수 있습니다.
  – 오버로드된 생성자의 이름(클래스 이름)은 같지만 인수 수는 다릅니다.
  – 전달된 인수의 수와 유형에 따라 특정 생성자가 호출됩니다.
• 여러 개의 생성자가 필요한 경우 오버로드된 함수로 구현됩니다.
• 소멸자를 오버로드할 수 없습니다.

목적:
• 여러 가지 초기화 방법을 사용하여 클래스의 유연성을 높이고
• 객체 배열을 지원
– Ex) Unit temp[2];

ex)


#include <iostream>

using namespace std;

class Unit {
private:
	int level,type;

public:
	Unit() {
		level = 0; type = 0;
	}

	Unit(int n) {
		level = n;
		type = 0;
	}

	Unit(int n, int m) {
		level = n;
		type = m;
	}
	int GetLevel() {
		return level;
	}

	int GetType() {
		return type;
	}
};

int main() {
	Unit A[4];
	Unit B[4] = { 1,2,3,4 };
	Unit C[4] = { {1,2},{3,4},{5,6},{7,8} };

	for (int i = 0; i < 4; i++) {
		cout << "A[" << i << "] : " << "level = " << A[i].GetLevel() << " type = " << A[i].GetType() << "\n";
		cout << "B[" << i << "] : " << "level = " << B[i].GetLevel() << " type = " << B[i].GetType() << "\n";
		cout << "C[" << i << "] : " << "level = " << C[i].GetLevel() << " type = " << C[i].GetType() << "\n";
	}
}

결과:
A[0] : level = 0 type = 0
B[0] : level = 1 type = 0
C[0] : level = 1 type = 2
A[1] : level = 0 type = 0
B[1] : level = 2 type = 0
C[1] : level = 3 type = 4
A[2] : level = 0 type = 0
B[2] : level = 3 type = 0
C[2] : level = 5 type = 6
A[3] : level = 0 type = 0
B[3] : level = 4 type = 0
C[3] : level = 7 type = 8

생성자 오버로딩을 통해 매개변수를 여러개 받는 객체들의 배열도
Unit A[4];
Unit B[4] = { 1,2,3,4 };
Unit C[4] = { {1,2},{3,4},{5,6},{7,8} };
이와 같이 수월하게 받을 수 있다.

🔑복사 생성자

• 복사 생성자는 다른 개체를 사용하여 개체를 초기화할 때 호출됩니다.
• 개체 대체(치환)에는 복사 생성자를 사용하지 않습니다.

Unit A;
Unit B=A;


Unit A,B;
Unit B=A;는 치환으로서 얕은 복사가 일어나지, 복사생성자 호출 x

메모리 생성자(및 복사생성자)호출에서 할당되고 소멸자에서 delete된다.

일반적인 복사 생성자

#define _CRT_SECURE_NO_WARNINGS
#define MAX_LEN 255
#include <iostream>


using namespace std;

class Unit {
	char* pszName;
public:
	Unit() {
		pszName = new char[MAX_LEN];
		cout << "Normal Constructor\n";
	}
	~Unit() {
		delete[] pszName;
	}

	Unit(const Unit& unit);

	void Print() {
		cout << pszName << "\n";
	}

	void Set(const char* pszIn) {
		strcpy(pszName, pszIn);
	}
};

Unit::Unit(const Unit& unit) {
	pszName = new char[MAX_LEN];
	strcpy(pszName, "Untitled");
	cout << "Copy Constructor\n";
}
int main() {
	Unit Zerg;
	Zerg.Set("zergling");
	Zerg.Print();

	Unit Spawn = Zerg;
	Spawn.Print();
}

Unit(const Unit& unit); 복사 생성자로 인해
A = B; 형태로 호출해도 복사 생성자가 호출된다.
위 코드의 main을

	Unit Zerg,Spawn;
	Zerg.Set("zergling");
	Zerg.Print();

	Spawn = Zerg;
	Spawn.Print();

와 같이 고치면 단순 치환으로 인식하며 Normal Constructor가 생성된다.

🔑디폴트 매개변수

• 프로그래머가 지정할 필요가 없는 함수에 대한 인수입니다.
• 프로그래머는 함수 호출 중에 인수가 지정되지 않은 경우에도 항상 값을 갖는 기본 인수를 지정할 수 있습니다.

void set(int x=0, int y=0);
set(); //0,0
set(1); //1,0
set(1,4); //1,4

디폴트 매개변수 퀴즈1

#include <iostream>

using namespace std;

class Unit {
	int x, y;

public:
	Unit(int x = 0, int y = 0) : x(x), y(y) {}

	int GetX() { return x; }
	int GetY() { return y; }
};
int main() {
	Unit A, B(10), C(10, 20);
	cout << "A: " << A.GetX() << "," << A.GetY() << "\n";
	cout << "B: " << B.GetX() << "," << B.GetY() << "\n";
	cout << "C: " << C.GetX() << "," << C.GetY() << "\n";
}

🔑C++ 문자열/문자 - 숫자 간 변환

atoi, itoa, stoi, to_string

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

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

void printStar(char b) {
	int c = b-'0';
	for (int i = 0; i < c; i++) {
		cout << "*";
	}
	cout << endl;
}

int main() {
	int a;
	char b;

	printf("Int : ");
	scanf("%d", &a);
	printf("Char : ");
	scanf("%*c%c", &b);

	printStar(a);
	printStar(b);
}
profile
컴퓨터와 교육 그사이 어딘가

0개의 댓글