39
11.string 클래스 디자인로딩 디자인로딩 표준 string 클래스 사용자 정의 클래스 사용자 정의 클래스 Jong Hyuk Park

11.string 클래스 디자인로딩 - Welcome to UCS Lab & Prof. … · 2010-11-28 · 11.string 클래스 디자인로딩 표준string 클래스 사용자정의클래스 Jong Hyuk

  • Upload
    dothuy

  • View
    223

  • Download
    0

Embed Size (px)

Citation preview

11.string 클래스디자인로딩디자인로딩

표준 string 클래스

사용자 정의 클래스사용자 정의 클래스

Jong Hyuk Park

표준 string 클래스표준 string 클래스

Jong Hyuk Park

string 클래스

C++ 표준 라이브러리에서 정의된 문자열 처리 클래스

#include <iostream>#include <string>using std::endl;

string str4;cout<<"문자열 입력: ";g

using std::cout;using std::cin;using std::string;

int main()

자열 입력cin>>str4;cout<<"입력한 문자열: "<<str4<<endl;return 0;

}int main(){

string str1="Good ";string str2="morning";string str3=str1+str2;

t t 1 dlcout<<str1<<endl;cout<<str2<<endl;cout<<str3<<endl;str1+=str2;if(str1==str3) { //str1과 str3의 내용 비교.

Good

morning

G d icout<<"equal!"<<endl;

}

Good morning

equal!

문자열 입력: Hello!

입력한 문자열: Hello!입력한 문자열: Hello!

사용자 정의 string 클래스사용자 정의 string 클래스

Jong Hyuk Park

string 클래스 사용자 구현

앞 예의 표준 라이브러리를 이용한 string 클래스의사용자구현사용자구현

현string 클래스 사용자 구현생성자,소멸자,복사 생성자 정의

연산자 오버로딩+, =, +=, ==, <<, >> 연산자 오버로딩

사용자 정의 string 클래스, 생성자 소멸자생성자, 소멸자

#include <iostream>

using std::endl;using std::cout;using std::cin;

i td t

// 생성자string::string(const char* s){

len=(s!=NULL ? strlen(s)+1 : 1);using std::ostream;using std::istream;

class string {int len; // null 문자를 포함하는 문자열의 길이

len=(s!=NULL ? strlen(s)+1 : 1);str=new char[len];if(s!=NULL)

strcpy(str, s);}

char* str;public:

string(const char* s=NULL);string(const string& s);~string();

// 복사 생성자string::string(const string& s){

len=s.len;string();

string& operator=(const string& s);string& operator+=(const string& s);bool operator==(const string& s);t i t ( t t i & )

;str=new char[len];strcpy(str, s.str);

}

// 소멸자string operator+(const string& s);

friend ostream& operator<<(ostream& os, const string& s);friend istream& operator>>(istream& is, string& s);

};

// 소멸자string::~string(){

delete []str;}

연산자 오버로딩

string& string::operator=(const string& s)i i i &{

delete []str;len=s.len;str=new char[len];strcpy(str, s.str);

string string::operator+(const string& s){

char* tStr=new char[len+s.len-1];strcpy(tStr, str);strcat(tStr, s.str);py( , );

return *this;}

string& string::operator+=(const string& s){

( , );

string temp(tStr);delete []tStr;return temp;

}{len=len+s.len-1;char* tStr=new char[len];strcpy(tStr, str);delete []str;t t(tSt t )

}

ostream& operator<<(ostream& os, const string& s){

os<<s.str;tstrcat(tStr, s.str);

str=tStr;return *this;

}

return os;}

istream& operator>>(istream& is, string& s){

bool string::operator==(const string& s){

return strcmp(str, s.str)? false:true;}

char str[100];is>>str;s=string(str);return is;

}}

실행결과

int main()int main(){

string str1="Good ";string str2="morning";string str3=str1+str2;cout<<str1<<endl;cout<<str2<<endl;cout<<str3<<endl;str1+=str2;

Good

morning

Good morning

if(str1==str3) { //str1과 str3의 내용 비교.cout<<"equal!"<<endl;

}string str4;

equal!

문자열 입력: Hello!

입력한 문자열: Hello!

cout<<"문자열 입력: ";cin>>str4;cout<<"입력한 문자열: "<<str4<<endl;

return 0;}

12. 템플릿(Template)

함수 템플릿

클래스 템플릿클래스 템플릿

Jong Hyuk Park

함수 템플릿함수 템플릿

Jong Hyuk Park

함수 템플릿 소개

함수 템플릿한번의 함수 정의로 서로 다른 자료형에 대해한번의 함수 정의로 서로 다른 자료형에 대해적용하는 함수

예int abs(int n) // 정수형 인수의 abs() 함수{ return n < 0 ? -n : n; }{ return n < 0 ? n : n; }

double abs(double n) // double 형 인수의 abs() 함수함수{ return n < 0 ? -n : n; }

함수의 인수와 반환형의 자료형 만이 다르 함수 내부의 로 램• 함수의 인수와 반환형의 자료형 만이 다르고 함수 내부의 프로그램코드는 모두 같음

• 템플릿 함수를 사용하여 함수 정의는 한번 만 하고 필요 시자료형에 따라 각각 적용자료형에 따라 각각 적용

11C++ Programming

함수 템플릿 정의

함수 템플릿은 template 키워드, typename(또는 class) 템플릿 자료형 인수들를 선언템플릿 자료형 인수들를 선언

템플릿의 자료형이 되어 템플릿 함수의 가인수나반환형을 위한 자료형으로 사용반환형을 위한 자 형 사용

template <typename Type1 [, typename Type 2 ……]>반환형 함수명(가인수 리스트)반환형 함수명(가인수 리스트){

………………

함수 호출 시에 사용되는 실인수, 반환형의 자료형을

}

컴파일러가 템플릿 함수의 자료형 인수에 대입하여 특정함수를 생성하고 호출

12C++ Programming

함수 템플릿 사용 예

template <class T>T abs(T n) // T 형 가인수, 반환형을 갖는 템플릿 함수 abs() 정의( ) // 형 가인수, 반환형을 갖는 템플릿 함수 () 정의{ return n < 0 ? –n : n; }

main(){

int i = abs(123); // int abs(int n)을 생성하고 호출double d = abs(-123.45); // double abs(double n)을 생성하고 호출( ); // ( )을 생성하 출

}

=> 함수 호출 시에 사용된 실인수, 반환형의 자료형에 따라 두 개의 abs() 함수를 함수 호출 시에 사용된 실인수, 반환형의 자료형에 따라 두 개의 abs() 함수를생성하고호출

i t b (i t ) // i t i b (123) 호출 시 생성int abs(int n) // int i = abs(123); 호출 시 생성{ return n < 0 ? –n : n; }double abs(double n) // double d = abs(-123.45); 호출 시 생성{ return n < 0 ? –n : n; }{ etu 0 ? : ; }

13C++ Programming

템플릿 자료형인수 사용 예인수 사용 예

템플릿 함수의 정의 시 사용되는 템플릿의자 형 인수는 함수의 가인수 최소한 한번자료형 인수는 함수의 가인수로 최소한 한번이상 사용되어야 함

• template <typenameT>T func1(T *a); // 올바름

• template <typename T>T func2(T a, T b); // 올바름

• template <typename T, typename T>T func2(T a, T b); // 에러, T가 중복 선언

• template <typename T, typename U>T f 2(T U b) // 올바름T func2(T a, U b); // 올바름

• template <typename T, typename U, typename V>U func2(T a, V b); // 에러, U가 가인수로 사용되지 않음

C++ Programming14

함수 템플릿 사용 예 1#include <iostream>using std::endl;using std::cout;

template <typename Type>Type min(Type a, Type b) // 템플릿 함수 min() 정의{ return a < b ? a : b; }

int main(){

// int min(int,int) 템플릿 함수 생성,호출i 88 2 dlcout << min(88,24) << endl;

// double min(double,double) 템플릿 함수 생성 및 호출cout << min(1.234,7.56) << endl;

0

24

1.234

return 0;}

min(88,24)의 호출 시에 템플릿의 자료형 인수 Type이 int로 치환된 int min(int, int)인 함수가

생성되고, min(1.234, 7.56)의 호출 시에는 double min(double, double)인 함수가 생성

15C++ Programming

함수 템플릿 사용 예 2

#include <iostream>using std::endl;using std::cout;

#include <iostream>using std::endl;using std::cout;

template <typename T> // 함수 템플릿정의

void ShowData(T a, T b) {

template <typename T1, typename T2> // 함수 템플릿정의

void ShowData(T1 a, T2 b) {{

cout<<a<<endl;cout<<b<<endl;

}

{cout<<a<<endl;cout<<b<<endl;

}

int main(void){

ShowData(1, 2);ShowData(3 2 5); // ! error

int main(void){

ShowData(1, 2);Sh D (3 2 5)ShowData(3, 2.5); // ! error

return 0;}

ShowData(3, 2.5);

return 0;}

16C++ Programming

함수 템플릿의 특수화

#include <iostream>using std::endl;

#include <iostream>using std::endl;using std::cout;using std::endl;

using std::cout;

template <typename T> // 함수 템플릿 정의int SizeOf(T a) {

using std::cout;template <typename T> // 함수 템플릿 정의int SizeOf(T a) {

return sizeof(a);{

return sizeof(a);}

int main(void)

}template<> // 함수 템플릿 정의int SizeOf(char* a) {

return strlen(a);{

int i=10;double e=7.7;char* str="Good morning!";

( );}int main(void){

int i=10;double e=7 7;

cout<<SizeOf(i)<<endl;cout<<SizeOf(e)<<endl;cout<<SizeOf(str)<<endl;

return 0;

double e=7.7;char* str="Good morning!";

cout<<SizeOf(i)<<endl;cout<<SizeOf(e)<<endl;

Si Of dlreturn 0;}

cout<<SizeOf(str)<<endl;

return 0;}

17C++ Programming

클래스 템플릿클래스 템플릿

Jong Hyuk Park

클래스 템플릿

클래스 템플릿한번의 클래스 정의로 서로 다른 자료형에 대해 적용하는클래스

class Counter {int value;

class Counter {double value;

public:Counter(int n) { value = n; }Counter() { value = 0; }

public:Counter(double n) { value = n; }Counter() { value = 0; }

int val() { return value; }void operator ++() { ++value; }void operator --() { --value; }

}

double val() { return value; }void operator ++() { ++value; }void operator --() { --value; }

}}; };

C++ Programming19

클래스 템플릿 정의 및생성생성

template <typename Type1 [, typename Type 2 ……]>class 클래스명 {

………………}

클래스명 <자료형 [,자료형,…]> 객체명;

template <typename T>class Counter {

T value;public:

Counter(T n) { value = n; }C t () { l 0 }

Counter <int> oi;Counter() { value = 0; }T val() { return value; }void operator ++() { ++value; }void operator () { value; }

Counter <double> od;

void operator --() { --value; }

20C++ Programming

클래스 템플릿 사용 예 1#include <iostream>using std::endl;using std::cout;

#include <iostream>using std::endl;using std::cout;template <typename T>

class Counter { template <typename T>

class Counter { T value;

public:Counter(T n) { value = n; }

{T value;

public:Counter(T n); Counter() { value = 0; }T val();Counter(T n) { value = n; }

Counter() { value = 0; }T val() { return value; }void operator ++() { ++value; }void operator --() { --value; }

}

T val(); void operator ++(); { ++value; }void operator --() { --value; }

};template <typename T>

C T C (T )};int main(void){

Counter <int> icnt; Counter <double> dcnt(3.14);

Counter<T>::Counter(T n){ value = n; }template <typename T>

T Counter<T>::val(){ return value; }( );

Counter <char> ccnt('C');

++icnt; --dcnt; ++ccnt;cout << "++icnt : " << icnt.val() << endl;cout << "--dcnt : " << dcnt val() << endl;

{ ; }

int main(void){

Counter <int> icnt; Counter <double> dcnt(3 14);cout << dcnt : << dcnt.val() << endl;

cout << "++ccnt : " << ccnt.val() << endl;

return 0;}

Counter <double> dcnt(3.14); Counter <char> ccnt('C');

++icnt; --dcnt; ++ccnt;cout << "++icnt : " << icnt.val() << endl;

t " d t " d t l() dlcout << "--dcnt : " << dcnt.val() << endl;cout << "++ccnt : " << ccnt.val() << endl;return 0;

}21

클래스 템플릿 사용 예 2#include <iostream>using std::endl;using std::cout;g

template <typename S, typename L>class Size {

int s;int l;

public:Size()

{ s = sizeof(S); l = sizeof(L); }void print()

{ cout << s << ',' << l << endl; }};

int main(void){

Size <char, long int> a;Size <float, double> b;

cout << "char,long int: "; a.print();cout << "float,double : "; b.print();

return 0;}

22C++ Programming

클래스 템플릿의 상속

클래스 템플릿도 일반 클래스와같이 상속

template <typename T>class Base {

……

같이 상속베이스 클래스인 클래스템플릿을 일반 클래스가 파생클래스가 되어 상속받는 경우 };

class Derive : public Base<int> {……

}

클래스가 되어 상속받는 경우• 베이스 클래스인 클래스

템플릿으로 부터 생성된클래스를 상속 }

template <typename T>

클래스를 상속• 클래스 템플릿을 생성하지

않고 전체를 상속 받으면 에러

template <typename T>class Base {

……};

클래스 템플릿인 베이스클래스로부터 클래스 템플릿인파생 클래스가 상속받는 경우 template <typename U>

class Derive : public Base<U> {……

}

파생 클래스가 상속받는 경우

}

23C++ Programming

클래스 템플릿의 상속 예#include <iostream>using std::endl;using std::cout;

int main(void){

Rectangle <int> ir(3,14);Rectangle <double> dr(2 5 7 3);

template <typename T>

class Area { // 베이스 클래스 템플릿T side1, side2;

public:

Rectangle <double> dr(2.5, 7.3);

cout << "int area : " << ir.getarea() << endl;cout << "double area : " << dr.getarea() << endl;

public:Area(T s1, T s2) // 생성자

{ side1 = s1; side2 = s2; }void getside(T &s1, T &s2)

{ s1 = side1; s2 = side2; }}

int area : 42

return 0;}

};

template <typename U>class Rectangle : public Area<U> {

// 파생 클래스 템플릿

double area : 18.25

클래스 템플릿인 파생 클래스 Rectangle이 또 다른public:

Rectangle(U s1, U s2) : Area<U>(s1,s2) // 생성자{ /* no operation */ }

U getarea(void){

클래스 템플릿인 파생 클래스 Rectangle이 또 다른

클래스 템플릿인 베이스 클래스 Area로부터 상속받

는 예이다. Rectangle 파생 클래스 템플릿는 Area

베이스 클래스 템플릿전체를 상속받는다.{U s1, s2;

getside(s1,s2); return s1 * s2;

}

베이스 클래스 템플릿전체를 상속받는다.

}};

24C++ Programming

13. 예외처리13. 예외처리

기존의 예외처리 방식기존의 예외처리 방식

C++ 예외처리

Jong Hyuk Park

예외처리 소개

예외처리(exception handling) 프로그램의 비정상적인 상황 발생 시 처리하는 과정

대개의 경우 예외처리 하지 않는 경우 실행에러 발생

26C++ Programming

예외처리 없는 코드 예

#include <iostream>using std::endl;using std::cout;

실행결과 1g

using std::cin;

int main(void)

{

두개의 숫자 입력 : 5 2

a/b의 몫 : 2

a/b의 나머지 : 1{int a, b;

cout<<"두개의 숫자 입력 : ";cin>>a>>b;

/ 의 나머지

실행결과 2

cout<<"a/b의 몫 : "<<a/b<<endl;cout<<"a/b의 나머지 : "<<a%b<<endl;

return 0;

실행결과

두개의 숫자 입력 : 5 0

<- !!! 실행에러 발생}

27C++ Programming

전통적 스타일 예외처리코드 예코드 예

#include <iostream>using std::endl;using std::cout;using std::cin;

실행결과 1g

int main(void){

int a, b;

두개의 숫자 입력 : 5 2

a/b의 몫 : 2

a/b의 나머지 : 1cout<<"두개의숫자입력 : ";cin>>a>>b;if(b==0){

cout<<"입력오류! 다시실행하세요."<<endl;}

/ 의 나머지

실행결과 2}else {

cout<<"a/b의몫 : "<<a/b<<endl;cout<<"a/b의나머지 : "<<a%b<<endl;

}

실행결과

두개의 숫자 입력 : 5 0

입력오류! 다시 실행 하세요.

return 0;}

28C++ Programming

C++ 예외처리C++ 예외처리

Jong Hyuk Park

C++ 예외처리 (1)

try & catchy

try {

/* 예외 발생 예상 지역 *// 예외 발생 예상 지역 /

}

catch(처리 되어야 할 예외의 종류) {

/* 예외를 처리하는 코드가 존재할 위치 */

}

throw

throw ex; // ex를 가리켜 보통은 그냥 “예외”라고 표현을 한다.

// 예외상황 발생 통보 시 사용

30C++ Programming

C++ 예외처리 (2)

31C++ Programming

C++ 예외처리 코드 예 1

#include <iostream>using std::endl;using std::cout;

실행결과 1

두개의 숫자 입력 : 5 2

실행결과 2

두개의 숫자 입력 : 5 0using std::cout;using std::cin;

int main(void){

int a b;

두개의 숫자 입력 : 5 2

a/b의 몫 : 2

a/b의 나머지 : 1

두개의 숫자 입력 : 5 0

0 입력.

입력오류! 다시 실행 하세요.

int a, b;

cout<<"두개의 숫자 입력 : ";cin>>a>>b;try{

if(b==0)throw b;

cout<<"a/b의 몫 : "<<a/b<<endl;cout<<"a/b의 나머지 : "<<a%b<<endl;

}}catch(int exception){

cout<<exception<<" 입력."<<endl; cout<<"입력오류! 다시 실행 하세요."<<endl;

}return 0;return 0;

}

32C++ Programming

C++ 예외처리 코드 예 2#include <iostream>using std::endl;using std::cout;using std::cin;

두개의 숫자 입력 : 5 0

0 입력.

입력오류! 다시 실행 하세요.

int divide(int a, int b); // a/b의 몫만 반환

int main(void){{

int a, b;

cout<<"두개의 숫자 입력 : ";cin>>a>>b;try{try{

cout<<"a/b의 몫 : "<<divide(a, b)<<endl;}catch(int exception){

cout<<exception<<" 입력."<<endl; 입력 다시 실행 하세 dlcout<<"입력오류! 다시 실행 하세요."<<endl;

}return 0;

}

int divide(int a, int b){

if(b==0)throw b;

return a/b;return a/b;}

33C++ Programming

스택 풀기(Stack Unwinding)(Stack Unwinding)

34C++ Programming

C++ 예외처리 코드 예

예외가 처리되지 않으면함 출• stdlib.h에 선언되어 있는 abort 함수의 호출에 의해 프로그램

종료

전달되는 예외 명시• 그 이외의 예외가 전달되면 abort 함수의 호출

i t f t(d bl d) th (i t d bl h *)int fct(double d) throw (int, double, char *)

{

. . . . .

}

C++ Programming35

C++ 예외처리 코드 예 3#include <iostream>using std::endl;using std::cout;using std::cin;using std::cin;int divide(int a, int b); // a/b의 몫만 반환int main(void){

int a, b;int a, b;

cout<<"두개의 숫자 입력 : ";cin>>a>>b;try{y{

cout<<"a/b의 몫 : "<<divide(a, b)<<endl;}catch(char exception){

cout<<exception<<" 입력."<<endl; p 입력 ;cout<<"입력오류! 다시 실행 하세요."<<endl;

}return 0;

}}int divide(int a, int b){

if(b==0)throw b; // !! 에러, int 형 b 전달; // 에러, 형 전달

return a/b;}

36C++ Programming

C++ 예외처리 코드 예 4

#include <iostream>using std::endl;g ;using std::cout;using std::cin;

int main(void){ 실행결과 1{

int num;

cout<<"input number: ";cin>>num;

{

input number: 10

int형 예외 발생try{

if(num>0)throw 10; // int형 예외 전달.

elsethrow 'm'; // char형 예외 전달.

실행결과 2형 예외 달

}catch(int exp){

cout<<"int형 예외 발생"<<endl;}catch(char exp){

input number: -10

char형 예외 발생catch(char exp){

cout<<"char형 예외 발생"<<endl;}return 0;

}

37C++ Programming

예외처리 클래스 예#include <iostream>using std::endl;using std::cout;using std::cin;

int main(void){

char acc[10];int id;

char* account="1234-5678"; //계좌번호int sid=1122; //비밀번호int balance=1000; //잔액.

int money;try{

cout<<"계좌번호 입력: ";cin>>acc;cout<<"비밀번호 4자리 입력: ";

class AccountExpt{

char acc[10];int sid;

public:

cout 비밀번호 4자리 입력: ;cin>>id;if(strcmp(account, acc) || sid!=id)

throw AccountExpt(acc, id);

cout<<"출금액 입력: ";public:AccountExpt(char* str, int id){

strcpy(acc, str);sid=id;

}d h

cout<< 출금액 입력: ;cin>>money;if(balance<money)

throw money;

b lvoid What(){cout<<"계좌번호: "<<acc<<endl;cout<<"비밀번호: "<<sid<<endl;

}};

balance-=money;cout<<"잔액: "<<balance<<endl;

}catch(int money){

cout<<"부족 금액: "<<money-balance<<endl;}; 부족 금액 y ;}catch(AccountExpt& expt){

cout<<"다음 입력을 다시 한번 확인 하세요"<<endl;expt.What();

}}return 0;

}

38C++ Programming

Jong Hyuk Park