overloading

:함수의 이름은 동일하나 매개변수의 type과 개수에 따라 다른함수로 인식 가능하다. return type은 고려하지않는다.

(signature=함수이름+매개변수. 즉 signature가 다르면 다른함수로 인식한다.)

ex)

1)abs (int)

2)abs (double)

3)abs (float)

1,2,3,은 각각 다른 함수이다. 하지만 사용이가능하다. 이는 overloading의 특성을 이용한 것이다.

overloading을 통하여 동일 명의 함수를 여러개 선언하는 경우 내용(body)는 동일하게 하는 것이 약속이다.

compatible

:변수 알아서 조정. promotion, demotion으로 나뉜다.

promotion:int -> double처럼 한단계 up 하는 것. data손실이 없다.

demotion:double->int처럼 한단계 down 하는 것. data 손실이 있다.(내림)

-->이러한 promotion 과 demotion은 최대한 피해주도록한다. type에 주의한다

default argument

:매개변수에 default값 적용하기

사용방법

=를 넣어주면된다.

이때 함수의 선언부분에서만 default값 설정이 가능하다.

default를 받는 구조

(int a1=1, int a2=2, int a3=3) 라는 함수가 있을 때

함수에서

funtiontest(1,2)-->이런식으로 써주었을 때 함수는 앞부터 숫자를 받게 되어 맨뒤 a3는 default값이 나오게된다.

이러한 특성으로 인해

(int a1=1, int a2, int a3)

이런식으로 쓴후에 funtiontest(1,2) 이런식으로 쓰게되면 함수는 1을 a1, 2를 a2에 저장해주게 된다.

a3는 default가 설정되있지 않으므로 본 파일은 애러가 뜬다.

따라서 default할때 주의점

1)선언에서 뒤쪽 매개변수부터 default값을 설정해주어야한다.

2)중간만 default설정은 불가능하다.

3)함수 호출시 앞쪽(왼쪽)부터 순차적으로 변수가 체워짐에 유의하자.

overloading, default 응용 코딩

문제

1) 더블타입의 pSample[5] = { 0.3,0.6,0.1,0.4,0.8 }; 이러한 배열이 있을 때

임의의 숫자 k를 입력한다.

그러면 k와 pSample[5]의 차이중 가장 작은 pSample[m]을 출력하고 그때의 차이를구하라

2) 1)과 동일하지만 이를 int형으로 받는다. 이때 함수의 이름은 1)과 동일하다(overloading). 또한 default를 이용하여 true이면 두수의 차이를 출력하고 false이면 pSample-target이 가장 작은 수를 출력하도록 지정하라.

#include "stdafx.h"

#include<iostream></iostream>

using namespace std;

//array를 reference 로 넘기기

double FindClosetPoint(double pSample[], int nSizeOfArray, double target, double& nearest)

{

int i;

int line = 0;

double val;

double ab[5];

double diff;

for (i = 0; i < 5; i++)

{ //ab배열에 숫자의 차이를 쭉 써주고

val = target - pSample[i];

ab[i] = abs(val);

}

//, 가장 차이가 작은것을 for 문을 통하여 . if를써서 저장될때 값을

// 한변수에 넣고 그때의 diff에 저장. 만약 ab의 배열이

diff = ab[0];

for (i = 0; i < 5; i++)

{

if (diff >= ab[i])

{

diff = ab[i];

line = i;

}

}

nearest = pSample[line];

return diff;

}

int FindClosetPoint(int pSample[], int nSizeOfArray, int target, int& nearest,bool bAbsDiff=true)

{

int i;

int arr[5];

int value=0;

int diff;

if (bAbsDiff == true)

{

for (i=0;i<5;i++)

{

arr[i] = abs(pSample[i]-target);

}

for (i = 0; i<5; i++)

{

value = arr[value] < arr[i] ? value : i;

}

diff = pSample[value] - target;

nearest = pSample[value];

return diff;

}

else

{

//arr[i]에 샘플과 타겟값의 차를 구한다.

for (i = 0; i<5; i++)

{

arr[i] = pSample[i] - target;

}

//arr[i]중 가장큰값이 몇번째 항인지 구한다.

for (i = 0; i<5; i++)

{

value = arr[i] > arr[value] ? value : i;

}

diff = pSample[value] - target;

nearest = pSample[value];

return diff;

}

}

int main()

{

double pSample[5] = { 0.3,0.6,0.1,0.4,0.8 };

double target;

double diff;

cout << "typing double type number here:";

cin >> target;

int nSizeOfArray = 5;

double nearest;

diff = FindClosetPoint(pSample, nSizeOfArray, target, nearest);

cout << "difference:" << diff << endl << "nearest value:" << nearest<<endl;

int pSampleInt[5] = { 3,6,1,4,8 };

int inttarget;

int intdiff;

cout << "typing int type number here:";

cin >> inttarget;

int intnearest;

intdiff = FindClosetPoint(pSampleInt, nSizeOfArray, inttarget, intnearest, false);

cout << "difference:" << intdiff << endl << "nearest value:" << intnearest;

return 0;

}
{.cpp}
#include <string>

#include <iostream>

#include "stdafx.h"


using namespace std;


int AmIWin(string strRPCInput, string strRPCCom)

{

int nWin;

if (strRPCInput == "rock")

{

if (strRPCCom == "rock")

{

return nWin = 0;

}

else if (strRPCCom == "scissor")

{

return nWin = 1;

}

else if (strRPCCom == "paper")

{

return nWin = -1;

}

else

{

return nWin = -8;

}

}

if (strRPCInput == "scissor")

{

if (strRPCCom == "rock")

{

return nWin = -1;

}

else if (strRPCCom == "scissor")

{

return nWin = 0;

}

else if (strRPCCom == "paper")

{

return nWin = 1;

}

else

{

return nWin = -8;

}

}

if (strRPCInput == "paper")

{

if (strRPCCom == "rock")

{

return nWin = 1;

}

else if (strRPCCom == "scissor")

{

return nWin = -1;

}

else if (strRPCCom == "paper")

{

return nWin = 0;

}

else

{

return nWin = -8;

}

}

}


#소스파일



#include "stdafx.h"

#include <iostream>

#include <cmath>

#include <time.h>

#include <string>

using namespace std;


int main()

{

cout << "let's play rsp game!";

int AmIWin(string strRPCInput, string strRPCCom);

//시간을 랜덤하게 sequence가 시간에 맞추어 배열

srand((unsigned int)time(0));

while (1)

{

int result;

cout << "sel rock,scissor,paper:"<<endl;

string rsp;

string pcrsp;

cin >> rsp;

int ran = rand() % 3;


if (ran == 0)

{

pcrsp = "rock";

}

else if (ran == 1)

{

pcrsp = "scissor";

}

else

{

pcrsp = "paper";

}

result = AmIWin(rsp,pcrsp);


switch(result)

{

case 1:

cout << "uwin!"<<endl << "pc is :"<< pcrsp <<endl;

break;

case -1:

cout << "ufail"<<endl<< "pc is :" << pcrsp << endl;

break;

case -8:

cout << "u are idiot"<<endl<< "pc is :" << pcrsp << endl;


}

}

return 0;

}

function

라이브러리에 짜여져 있는 함수 불러오기.

#incluce <함수명> -- 이런식으로 불러온다.

#include

#include --math.h cmath 둘다 동일함수. .h로 끝나는 것은 c의 잔해

각종함수 사용하기. (루트)

       {.cpp}
       //sqrt
        #include "stdafx.h"

        #include <iostream>

        #include <cmath>

        using namespace std;

        int main()

        {

        double c = 4;

        double d = sqrt(c);

        cout << d;

        return 0;

        }

       //abs(절댓값을 구하는 함수이다.)
       #include "stdafx.h"

#include <iostream>

using namespace std;

int main()

{

int a = -16;

int b;

b = abs(a);

cout << b;

}.

void의 역할

값을 리턴하여 준다.

랜덤으로 숫자만들기

기본적으로 cmath를 import 한후에 rand()를 사용함.
하지만 이렇게 호출하면 rand의 일정 sequence가 출력된다.
이는 프로그램을 종료했다 시작할 때 random값이 다시 rewind 된다.
따라서 sequence를 일정하지 않게 하려면 srand(unsigned int형 값만 받는다.)를 한후에 time값을 준다.
예제는 밑에서 보이도록 하겠다.

함수만들기

함수는 declaration/definition/call로 나뉜다.

함수를 선언하는 것을 declaration이라 한다.

type 이름 (매개변수) 꼴이다.

함수의 head part만 적고 ;를 누르면 선언이 된다.

정의 definition

{} ---> body를 적으면 definition이다.

definition 은 1회만 정의된다.

그러나 선언은 다수 정의될 수 없다.

-정의의 예제.(만약 함수를 call한후 뒤에서 선언 및 초기화시 사용 불가능.

-but 선언을 하고 함수를 사용하고 뒤에서 정의하는 것은 사용가능. 이는 이중 함수문 사용 불가능하다.

-함수의 선언

반환자료형 함수명(변수)

에서 반환자료형을 void로 받으면 return 하지 않는다.

-c는 함수를 실행시킬 때 main함수부터 실행시킨다.

{.cpp}
#include "stdafx.h"
#include <iostream>
using namespace std;
void sum(int a, int b)
{
int c = a + b;
cout << c<<endl;
}

int mul(int a, int b)
{
int cc = a*b;

return cc;
}

int main()

{
int a, b,c;
a = 10;
b = 40;
sum(10, 20);
cout << a;
c=mul(a, b);
cout << c;
}

함수에대한더 깊은 고찰

.cpp 파일가 .h 파일이 있다.

.h 는 보통 함수를 정의하고 클래스를 정의하기 위하여 사용한다.

.cpp에서 만든 함수를 다른 .cpp내에서 사용하고 싶다면

이런 소스파일내에 같이 있는 상태로

sum.cpp에서 함수를 만들어주면

{.cpp}  
int sum(int a, int b)

{

int c;

c = a + b;

return c;

}

consoleapplication에서 선언한번 해주면된다.

// ConsoleApplication14.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.

//

#include "stdafx.h"

#include <iostream>

using namespace std;

int main()

{

int sum(int a, int b);

int a = 10;

int b = 20;

int c;

c = sum(a, b);

cout << c;

return 0;

}

하지만 일일이 이렇게 하기는 상당히 불편하다

#.h파일에 다음과같이 작성후

int sum(int a, int b);

#import 한번이면끝!

#include "stdafx.h"

#include <iostream>

#include "head.h"

using namespace std;

int main()

{

int a = 10;

int b = 20;

int c;

c = sum(a, b);

cout << c;

return 0;

}.

+ Recent posts