Created
November 14, 2012 18:10
-
-
Save Jack2/4073746 to your computer and use it in GitHub Desktop.
[C++]function_pointer_example2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <conio.h> | |
using namespace std; | |
int sum(int a,int b); | |
int subtract(int a,int b); | |
int multi(int a,int b); | |
int divide(int a,int b); | |
int(*p[4])(int x,int y) = {sum, subtract, multi, divide}; | |
int main() | |
{ | |
int result; | |
int num1, num2, operNum; | |
char oper; | |
cout << "두 수를 입력하세요 : " ; | |
cin >> num1 >> num2; | |
cout << "+: 더하기, -: 빼기, *: 곱하기, /: 나누기 " << endl; | |
do | |
{ | |
operNum = -1; | |
cout << "연산을 선택하세요 : "; | |
oper = cin.get(); //문자만 입력을 받을 때 cin.get() 사용 | |
switch(oper){ | |
case '+': | |
operNum = 0; | |
break; | |
case '-': | |
operNum = 1; | |
break; | |
case '*': | |
operNum = 2; | |
break; | |
case '/': | |
operNum = 3; | |
break; | |
} | |
} while (operNum>3 || operNum<0); | |
result = (*p[operNum])(num1, num2); | |
cout << "연산 결과 : " << result << endl; | |
return 0; | |
} | |
int sum(int a,int b) | |
{ | |
return a+b; | |
} | |
int subtract(int a,int b) | |
{ | |
return a-b; | |
} | |
int multi(int a,int b) | |
{ | |
return a*b; | |
} | |
int divide(int a,int b) | |
{ | |
if(a!=0 && b!=0){ | |
return a/b; | |
} else return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment