'Busan IT/제어 UI(C++)'에 해당되는 글 20건

  1. 2015.06.29 try/throw/catch 구문
  2. 2015.06.25 템플릿(3)
  3. 2015.06.24 템플릿(2)
  4. 2015.06.23 템플릿(1)
  5. 2015.06.22 다형성 - 순수 가상 함수
  6. 2015.06.18 연산자, 다형성
  7. 2015.06.17 다형성, 연산자 오버로딩
  8. 2015.06.16 다중상속
  9. 2015.06.15 상속과 한정자
  10. 2015.06.12 생성자, 소멸자, 복사생성자, 함수의 구현, cin, 상속
Busan IT/제어 UI(C++)2015. 6. 29. 17:17

================================ Outline ====================================

예외처리

- try/throw/catch 구문

----------------------------------------------------------------------------

 

try/throw/catch 구문

 

try: 수행하고자 하는 코드를 넣는다.

throw: 제어문을 넣어서 특정 조건에 해당되는 경우 throw를 사용하여 값 던진다.

catch: throw에서 받은 값을 사용자가 원하는 형(type)으로 받는다.

 

try-throw-catch문은 흐름문의 일종으로써 프로그램의 흐름을 알아볼 때 사용된다.

 

기본 문법은 다음과 같다.

 

try

{

if (예외 조건)

throw 예외 객체;

}

catch (예외 객체)

{

예외 처리

}

 

** try블록과 catch는 사이에는 다른 코드가 들어가서는 안된다. 

 


/*** try catch 구문 ***/
#include <iostream>

using namespace std;

void divide(int A, int B)
{
    if(0 == B)
    {
        throw B;        // B가 0일 경우 B를 catch로 던진다. throw가 실행되면 해당 함수는 종료된다. 
    }
    else if(0 == A)
    {
        throw A;        // A가 0일 경우 A를 catch로 던진다.
    }
    cout<<"몫은" << A/B <<"입니다.\n";
    cout<<"나머지는" << A%B <<"입니다.\n";
}

int main(void)
{
    int A, B;
    cout<< "나누고 싶은 숫자를 입력하세요" << endl;
    cin >> A ;
    cout<<"나눌 싶은 숫자를 입력하세요"<<endl;
    cin >> B;

    try
    { 
        divide(A, B);
        cout << "======================================================\n";
    }
    catch(int iTest)        //throw에서 받은 값을 int iTest에 넣는다.
    {
        cout << iTest << "로는 나눌 수 없습니다." <<endl;
    }

    return 0;
}

throw가 실행되면 해당 함수는 종료됨으로 return과 같은 역할을 하지만 다른 점이 있다면 throw문은 반환 값이 항상 존재한다는 것이다.

 

cout으로 표현한 ‘================’ 값이 try -catch 문의 작동여부에 따라 출력이 되는 것을 알 수 있다.

 

** exit 함수는 현재 열려 있는 파일들을 종료하고 닫도록 해주는 함수이다. 즉 잘 정돈 후 프로그램을 종료하도록 해주는 함수이다.



** catch문도 오버로딩이 가능함으로 throw의 값에 따라 실행하는 catch문을 따로 작성할 수 있다.

 

교재 p/407, 스택 되감기

#include <iostream>
#include <stdio.h>
using namespace std;

class C 
{
    int a;

    public:
        C()
        {
            puts("Creator called");
        }
        ~C()
        {
            puts("Destructor called");
        }
};

void divide(int a, int d)
{
    if(d==0)
        throw "0으로는 나눌 수 없습니다.";
    cout<<"나누기 결과 ="<<a/d<<"입니다.\n";
}

void calc(int t, const char *m)
{
    C c;
    divide(10,0);
}

int main(void)
{
    try
    {
        calc(1"계산");
    }
    catch(const char * message)
    {
        puts(message);
    }
    puts("프로그램이 종료됩니다.");


    return 0;
}

try - catch문을 중첩으로 사용하는 것도 가능하다.

 

교재 p/409, 중첩 try- catch



#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
using namespace std;

int main(void)
{
    int Num;
    int Age;
    char cBin;
    char Name[30];

    try
    {
        printf("학번을 입력하시오 : ");
        scanf("%d"&Num);
        if('\n'==(cBin=getchar()))
            ;
        if(Num <= 0)
            throw Num;
        try
        {
            printf("이름을 입력하시오 : ");
            gets(Name);
            if(strlen(Name) < 4)
                throw "이름이 너무 짧습니다.";
            printf("나이를 입력하시오 : ");
            scanf("%d"&Age);
            if(Age <= 0)
                throw Age;
            printf("입력한 정보 => 학번:%d, 이름:%s, 나이:%d\n", Num, Name, Age);
        }
        catch(const char *Message)
        {
            puts(Message);
        }
        catch(int)
        {
            throw;
        }
    }
    catch(int n)
    {
        printf("%d는 음수이므로 적합하지 않습니다.\n", n);
    }

    return 0;
}

catch 블록에서 예외를 다시 던질 때는 예외 객체를 지정할 필요 없이 throw 명령만 단독으로 사용한다. 받은 객체를 그대로 다시 넘기는 것이므로 예외 객체를 명시할 필요가 없으며 직접 처리하지 않으므로 catch의 괄호 안에 예외 객체의 이름을 줄 필요도 없다.

반응형

'Busan IT > 제어 UI(C++)' 카테고리의 다른 글

템플릿(3)  (0) 2015.06.25
템플릿(2)  (0) 2015.06.24
템플릿(1)  (0) 2015.06.23
다형성 - 순수 가상 함수  (0) 2015.06.22
연산자, 다형성  (0) 2015.06.18
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 25. 16:53

================================ Outline ====================================

템플릿

- 템플릿이 2개 이상인 경우

- default 인자

- 특수화

- 비타입 인수

----------------------------------------------------------------------------

템플릿이 2개 이상인 경우

 

 #include <iostream>


using namespace std;

template <class T, class T2>
T add(T fNum, T2 iNum)
{
    return fNum + (T)iNum;
}


int main(void)
{
    float fNum = 2.1;
    int iNum = 3;

    fNum = add<floatint>(fNum, iNum);
    cout << fNum << endl;
    
    return 0;
}

 

 

default 인자

 

int add(int Num1, Num2 = 2)

{

return Num1 + Num2;

}

 

특수화

#include <iostream>
#include <stdio.h>

using namespace std;

template <class T>
void Swap(T &a, T &b)
{
    T t;
    t=a;
    a=b;
    b=t;
}

template <> void Swap<double> (double &a, double &b)
{
    int i,j;

    i = (int)a;
    j = (int)b;
    a = a - i + j;
    b = b - j + i;
}

int main(void)
{
    double a=1.2, b=3.4;
    printf("before a = %g, b = %g\n", a, b);
    Swap(a,b);
    printf("after a = %g, b = %g\n", a, b);

    return 0;
}

 

 

 

비타입 인수

 

템플릿의 인수는 통상적으로 타입이 오지만, 인자를 사용하고자 할 때 쓰는 것이 비타입인수이다.

#include <iostream>
#include <stdio.h>

using namespace std;

template <typename T, int N>
class Array
{
    private:
        T ar[N];
    public:
        void SetAt(int n, T v)
        {
            if (n < N && n >= 0)
                ar[n] = v;
        }
        T GetAt(int n)
        {
            return (n < N && n >= 0 ? ar[n]:0);
        }
};

int main(void)
{
    Array<int5> ari;
    ari.SetAt(11234);
    ari.SetAt(10005678);
    printf("%d\n", ari.GetAt(1));
    printf("%d\n", ari.GetAt(5));

    return 0;
}

템플릿 변수 안에 쓸 것이 없는 경우 <>표시만 해준다.

#include <iostream>

using namespace std;

template <typename T>
class smart
{
    public:
        static T Num;

};
template <typename T>
T smart<T>::Num;

template <>
int smart<int>::Num=100;

int main(void)
{
    smart<int> obj1;
    smart<short> obj2;
    cout <<obj1.Num << endl;
    cout <<obj2.Num << endl;
    
    return 0;
}

 

 

 

반응형

'Busan IT > 제어 UI(C++)' 카테고리의 다른 글

try/throw/catch 구문  (0) 2015.06.29
템플릿(2)  (0) 2015.06.24
템플릿(1)  (0) 2015.06.23
다형성 - 순수 가상 함수  (0) 2015.06.22
연산자, 다형성  (0) 2015.06.18
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 24. 15:51

================================ Outline ====================================

템플레이트

----------------------------------------------------------------------------


//인라인과 템플레이트 코딩 내용은 헤더 파일에 있어야 한다.

 

 

#include <iostream>

using namespace std;

template <typename T>
class smart
{
    public :
        T Num;
        T test(T a);
        /*{
            Num = a;
            return Num;
        }*/


};
template <typename T>
T smart<T>:: test(T a)
{
    Num = a;
    return Num;
}

int main(void)
{
    smart <double> obj;
    obj.test(213.23);
    
    //obj.Num = 1;
    cout << obj.Num <<endl;
    return 0;
}





 

 

반응형

'Busan IT > 제어 UI(C++)' 카테고리의 다른 글

try/throw/catch 구문  (0) 2015.06.29
템플릿(3)  (0) 2015.06.25
템플릿(1)  (0) 2015.06.23
다형성 - 순수 가상 함수  (0) 2015.06.22
연산자, 다형성  (0) 2015.06.18
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 23. 16:48

================================ Outline ====================================

템플릿

----------------------------------------------------------------------------

교재 p/345 ch. 31 템플릿

 

 

템플릿(template)란 무엇인가를 만들기 위한 형틀이란 의미로 프로그램 일반화에 사용된다.

 

 

syntax,

 

template <typename *> // *자리에 예약어는 사용하지 못한다.

 

* add(* A, * B)

{

return A + B;

}

 

 

어셈블리 파일을 보면 명칭부호화를 통해 함수가 나누어져 있음을 알 수 있다.

 

이를 호출할 때는 타입을 명기해 주어야 한다.

 

ex) cout << add<int> (3, 2) << endl;

 

하지만 <int>는 생략 가능하다. 



개념을 잡기 위한 예제,


#include <iostream>

using namespace std;

/*int add(int A, int B)
  {
  return A + B;
  }*/


template <typename T>

T add(T A, T B)
{
    return A + B;
}

int main(void)
{
    cout<<add(1,2)<<endl;
    cout<<add(3.1,2.1)<<endl;

    return 0;
}



 

 

반응형

'Busan IT > 제어 UI(C++)' 카테고리의 다른 글

템플릿(3)  (0) 2015.06.25
템플릿(2)  (0) 2015.06.24
다형성 - 순수 가상 함수  (0) 2015.06.22
연산자, 다형성  (0) 2015.06.18
다형성, 연산자 오버로딩  (0) 2015.06.17
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 22. 16:12

================================ Outline ====================================

다형성 - 순수 가상 함수

----------------------------------------------------------------------------

 

순수 가상 함수(Pure Virtual Function)는 파생 클래스에서 반드시 재정의해야 하는 함수이다. 순수 가상 함수는 일반적으로 함수의 동작을 정의하는 본체를 가지지 않으며 따라서 이 상태에서는 생성이 불가능하다. 본체가 없다는 뜻으로 선언부 끝에 =0 이라는 표기를 하는데 이는 함수만 있고 코드는 비어 있다는 뜻이다.

 

순수 가상 함수는 클래스의 뼈대를 만들 때 사용한다. C#에서 인터페이스 개념과 같다.

 

ex) class Grapahic

{

public:

virtual void Draw() = 0;

}

 

class Line : public Graphic

{

virtual void Draw()

{

puts("선을 긋습니다.“);

}

}

 

int main(void)

{

Line obj;

obj.Draw();

 

return 0;

}

 

하나의 이상의 순수 가상 함수를 가지는 클래스를 추상 클래스(abstract class)라고 한다.

 

 

반응형

'Busan IT > 제어 UI(C++)' 카테고리의 다른 글

템플릿(2)  (0) 2015.06.24
템플릿(1)  (0) 2015.06.23
연산자, 다형성  (0) 2015.06.18
다형성, 연산자 오버로딩  (0) 2015.06.17
다중상속  (0) 2015.06.16
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 18. 17:02

================================ Outline ====================================

연산자

- Str 연산자

다형성

- 멤버함수가 호출하는 함수

- 가상 파괴자

----------------------------------------------------------------------------

연산자

Str 연산자

교재 p/235 

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <cstdlib>
#include <stdarg.h>
#include <stdio.h>
using namespace std;

class Str
{
    friend ostream &operator <<(ostream &c, const Str &S);
    friend const Str operator +(const char *ptr,Str &s);
    friend bool operator ==(const char *ptr,Str &s);
    friend bool operator !=(const char *ptr,Str &s);
    friend bool operator >(const char *ptr,Str &s);
    friend bool operator <(const char *ptr,Str &s);
    friend bool operator >=(const char *ptr,Str &s);
    friend bool operator <=(const char *ptr,Str &s);
    protected:
    char *buf;
    int size;

    public:
    Str();
    Str(const char *ptr);
    Str(const Str &Other);
    explicit Str(int num);
    virtual ~Str();

    int length() const { return strlen(buf); }
    Str& operator =(const Str &Other);
    Str& operator +=(Str &Other);
    Str& operator +=(const char *ptr);
    char& operator [](int idx) { return buf[idx]; }
    const char &operator [](int idx) const { return buf[idx]; }
    operator const char *() { return (const char *)buf; }
    operator int() { return atoi(buf); }
    const Str operator +(Str &Other) const;
    const Str operator +(const char *ptr) const { return *this+Str(ptr); }
    bool operator ==(Str &Other) { return strcmp(buf,Other.buf)==0; }
    bool operator ==(const char *ptr) { return strcmp(buf,ptr)==0; }
    bool operator !=(Str &Other) { return strcmp(buf,Other.buf)!=0; }
    bool operator !=(const char *ptr) { return strcmp(buf,ptr)!=0; }
    bool operator >(Str &Other) { return strcmp(buf,Other.buf)>0; }
    bool operator >(const char *ptr) { return strcmp(buf,ptr)>0; }
    bool operator <(Str &Other) { return strcmp(buf,Other.buf)<0; }
    bool operator <(const char *ptr) { return strcmp(buf,ptr)<0; }
    bool operator >=(Str &Other) { return strcmp(buf,Other.buf)>=0; }
    bool operator >=(const char *ptr) { return strcmp(buf,ptr)>=0; }
    bool operator <=(Str &Other) { return strcmp(buf,Other.buf)<=0; }
    bool operator <=(const char *ptr) { return strcmp(buf,ptr)<=0; }
    void Format(const char *fmt,...);
};

// 디폴트 생성자
Str::Str()
{
    size=1;
    buf=new char[size];
    buf[0]=0;
}

// 문자열로부터 생성하기
Str::Str(const char *ptr)
{
    size=strlen(ptr)+1;
    buf=new char[size];
    strcpy(buf,ptr);
}

// 복사 생성자
Str::Str(const Str &Other)
{
    size=Other.length()+1;
    buf=new char[size];
    strcpy(buf,Other.buf);
}

// 정수형 변환 생성자
Str::Str(int num)
{
    char temp[128];

    itoa(num,temp,10);
    size=strlen(temp)+1;
    buf=new char[size];
    strcpy(buf,temp);
}

// 파괴자
Str::~Str()
{
    delete [] buf;
}

// 대입 연산자
Str &Str::operator =(const Str &Other)
{
    if (this != &Other) {
        size=Other.length()+1;
        delete [] buf;
        buf=new char[size];
        strcpy(buf,Other.buf);
    }
    return *this;
}

// 복합 연결 연산자
Str &Str::operator +=(Str &Other)
{
    char *old;
    old=buf;
    size+=Other.length();
    buf=new char[size];
    strcpy(buf,old);
    strcat(buf,Other.buf);
    delete [] old;
    return *this;
}

Str &Str::operator +=(const char *ptr)
{
    return *this+=Str(ptr);
}

// 연결 연산자
const Str Str::operator +(Str &Other) const
{
    Str T;

    delete [] T.buf;
    T.size=length()+Other.length()+1;
    T.buf=new char[T.size];
    strcpy(T.buf,buf);
    strcat(T.buf,(const char *)Other);
    return T;
}

// 출력 연산자
ostream &operator <<(ostream &c, const Str &S)
{
    c<< S.buf;
    return c;
}

// 더하기 및 관계 연산자
const Str operator +(const char *ptr,Str &s) { return Str(ptr)+s;}
bool operator ==(const char *ptr,Str &s) { return strcmp(ptr,s.buf)==0;}
bool operator !=(const char *ptr,Str &s) { return strcmp(ptr,s.buf)!=0;}
bool operator >(const char *ptr,Str &s) { return strcmp(ptr,s.buf)>0;}
bool operator <(const char *ptr,Str &s) { return strcmp(ptr,s.buf)<0;}
bool operator >=(const char *ptr,Str &s) { return strcmp(ptr,s.buf)>=0;}
bool operator <=(const char *ptr,Str &s) { return strcmp(ptr,s.buf)<=0;}

// 서식 조립 함수
void Str::Format(const char *fmt,...)
{
    char temp[1024];
    va_list marker;

    va_start(marker, fmt);
    vsprintf(temp,fmt,marker);
    *this=Str(temp);
}


int main()
{
    Str s="125";
    int k;
    k=(int)s+123;

    Str s1("문자열");      // 문자열로 생성자
    Str s2(s1);                   // 복사 생성자
    Str s3;                    // 디폴트 생성자
    s3=s1;                    // 대입 연산자

    // 출력 연산자
    cout<< "s1=" << s1 << ",s2=" << s2<< ",s3=" << s3 << endl;
    cout<< "길이=" << s1 << endl;

    // 정수형 변환 생성자와 변환 연산자
    Str s4(1234);
    cout<< "s4=" << s4 << endl;
    int num=int(s4)+1;
    cout<< "num=" << num << endl;

    // 문자열 연결 테스트
    Str s5="First";
    Str s6="Second";
    cout<< s5+s6 << endl;
    cout<< s6+"Third" << endl;
    cout<< "Zero"+s5 << endl;
    cout<< "s1은 "+s1+"이고 s5는 "+s5+"이다." << endl;
    s5+=s6;
    cout<< "s5와 s6을 연결하면 " << s5 << "이다."<< endl;
    s5+="Concatination";
    cout<< "s5에 문자열을 덧붙이면 " << s5 << "이다."<< endl;

    // 비교 연산자 테스트
    if (s1 == s2) {
        cout<< "두 문자열은 같다." << endl;
    } else {
        cout<< "두 문자열은 다르다." << endl;
    }

    // char *형과의 연산 테스트
    Str s7;
    s7="상수 문자열";
    cout<< s7 << endl;
    char str[128];
    strcpy(str,s7);
    cout<< str << endl;

    // 첨자 연산자 테스트
    Str s8("Index");
    cout<< "s8[2]=" << s8[2<< endl;
    s8[2]='k';
    cout<< "s8[2]=" << s8[2<< endl;

    // 서식 조립 테스트
    Str sf;
    int i=9876;
    double d=1.234567;
    sf.Format("서식 조립 가능하다. 정수=%d, 실수=%.2f",i,d);
    cout<< sf << endl;

    return 0;
}



다형성

교재 p/322 다형성 -> 멤버 함수가 호출하는 함수 예제,


#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

class Point
 {
     protected:
   int x,y;
   char ch;

     public:
   Point(int ax, int ay, char ach)
   {
       x=ax;
       y=ay;
       ch=ach;
   }
   virtual void Show()
   {
       gotoxy(x,y);
             putch(ch);
         }
         virtual void Hide()
         {
             gotoxy(x,y);
             putch(' ');
         }
         void Move(int nx, int ny)
         {
             Hide();
             x=nx;
             y=ny;
             Show();
         }
 };

class Circle : public Point
 {
     protected:
         int Rad;

     public:
         Circle(int ax, int ay, char ach, int aRad) 
             : Point(ax, ay, ach)
         {
             Rad = aRad;
         }

         virtual void Show()
         {
       for(double a = 0; a < 360; a+=15)
             {
                 gotoxy(int(x+sin(a*3.14/180)*Rad), int(y-cos(a*3.14/180)*Rad));
                 putch(' ');
       }
   }
 };

int main(void)
 {


     Point P(1,1,'P');
     Circle C(10,10,'C',5);

     P.Show();
     C.Show();

     getch();
     P.Move(40,1);
     getch();
     C.Move(40,10);
     getch();
 }
   
  


교재 p/329 다형성 -> 가상 파괴자 예제,

#include <iostream>
#include <stdio.h>
using namespace std;

class Base
{
    private : 
        char *B_buf;
    public:
        Base()
        {
            B_buf = new char[10];
            puts("Base 생성");
        }
        virtual ~Base()
        {
            delete [] B_buf;
            puts("Base 파괴");
        }
};
class Derived : public Base
{
    private : 
        char *D_buf;
    public:
        Derived()
        {
            D_buf = new char[10];
            puts("Derived 생성");
        }
        virtual ~Derived()
        {
            delete [] D_buf;
            puts("Derived 파괴");
        }
};

        

int main(void)
{
    Base *pB;
    pB = new Derived;
    delete pB;
    return 0;
}
        

 

//생성자는 virtual 키워드를 사용할 수 없다.

 

소멸자에 virtual을 붙혀주면 아래와 같은 결과가 나온다.






반응형

'Busan IT > 제어 UI(C++)' 카테고리의 다른 글

템플릿(1)  (0) 2015.06.23
다형성 - 순수 가상 함수  (0) 2015.06.22
다형성, 연산자 오버로딩  (0) 2015.06.17
다중상속  (0) 2015.06.16
상속과 한정자  (0) 2015.06.15
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 17. 17:27

================================ Outline ====================================

다형성

-가상 함수

연산자 오버로딩

-복합 대입 연산자  

----------------------------------------------------------------------------

 

교재 p/301 ch.30 다형성

 

가상 함수

 

가상함수란 클래스 타입의 포인터로 멤버 함수를 호출할 때 동작하는 특별한 함수이다.

 

 

부모클래스(P)와 자식클래스(O)가 있는 경우,

 

P = O //대입 가능

O = P //대입 불가

 

자식클래스를 부모클래스에 대입할 때, 자식클래스만 가진 멤버가 부모클래스에 대입되지 못하는 일이 발생하는데 이를 슬라이스 문제라고 한다.

 

p/303 객체 포인터 예제,

#include <iostream>
#include <stdio.h>
#include <string.h>

class Human
{
    protected:
        char Name[16];
    public:
        Human(const char *aName)
        {
            strcpy(Name, aName);
        }
        void Intro()
        {
            printf("이름: %s", Name);
        }
        void Think()
        {
            puts("오늘 점심은 뭘 먹을까?");
        }
};

class Student : public Human
{
    private:
        int StNum;
    public:
            Student(const char *aName, int aStNum)
                : Human(aName)
            {
                StNum = aStNum;
            }
            void Intro()
            {
                Human::Intro();
                printf(",학번:%d\n",StNum);
            }
            void Think()
            {
                puts("이번 기말 고사 잘 쳐야 할텐데");
            }
            void Study()
            {
                puts("하늘 천 따지 검을 현 누를 황...");
            }
};

int main()
{
    Human H("김사람");
    Student S("이학생"1234567);
    Human *pH;
    Student *pS;

    pH = &H;
    pS = &S;
    pH=&S;
    //pS=&H;

    pS=(Student *)&H;
    pS->Intro();
    return 0;
}




virtual는 가상 함수를 선언하는 키워드이다. 위치는 함수의 앞이다. 가상함수는 포인터를 정적 타입이 아닌 동적 타입을 따르게 해주는 함수이다. 예제를 통해 가상함수의 기능을 살펴보자.

 

p/308 가상 함수 예제,


#include <iostream>

using namespace std;

class Base
{
    public:
        virtual void OutMessage()
        {
            cout<<"Base Class\n";
        }
};
class Derived: public Base 
{
    public:
        virtual void OutMessage()
        {
            cout<<"Derived Class\n";
        }
};

void Message(Base *pB)
{
    pB->OutMessage();
}

int main(void)
{
    Base B;
    Derived D;

    Message(&B);
    Message(&D);
    return 0;
}


부모 클래스형의 포인터로부터 멤버 함수를 호출할 때 비가상 함수는 포인터가 어떤 객체를 가리키는가에 상관없이 항상 포인터 타입 클래스의 멤버 함수를 호출한다. 반면 가상 함수는 포인터가 가리키는 실제 객체의 함수를 호출한다는 점이 다르다. 때문에 재정의가 생길 수 있는 함수는 가상으로 선언하는 것이 좋다.

 

 

virtual 함수의 최종 객체 타입으로 정의된 함수를 호출해준다. 컴파일 시 포인터가 가리키는 함수의 위치가 결정되는 것이 아니라 런타임 시 결정된다.


수업 시간에 작성한 추가 예제,



연산자 오버로딩 - 복합 대입 연산자


교재 p/219 복합 대입 연산자 예제,

#include <iostream>
#include <stdio.h>

using namespace std;

class Time
{
    int hour, min, sec;

    public:
        Time(){}
        Time(int h, int m, int s)
        {
            hour = h;
            min = m;
            sec = s;
        }
        void OutTime()
        {
            printf("%d: %d: %d\n", hour, min, sec);
        }
        Time &operator +=(int s)
        {
            sec += s;
            min += sec/60;
            sec %= 60;
            hour += min/60;
            min %= 60;
            return *this;
        }
};


int main(void)
{
    Time A(1,1,1);

    A+=100000;
    A.OutTime();

    return 0;
}



** 교재에 나와 있는 연산자에 대한 교재의 내용을 읽어보고 예제를 직접 작성해 본다.


반응형

'Busan IT > 제어 UI(C++)' 카테고리의 다른 글

다형성 - 순수 가상 함수  (0) 2015.06.22
연산자, 다형성  (0) 2015.06.18
다중상속  (0) 2015.06.16
상속과 한정자  (0) 2015.06.15
생성자, 소멸자, 복사생성자, 함수의 구현, cin, 상속  (0) 2015.06.12
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 16. 17:38

 

 

================================ Outline ====================================

다중상속

----------------------------------------------------------------------------

 

다중 상속을 받을 시 클래스 내부 변수가 겹칠 때는 스코프(::)를 사용하여 변수가 속한 위치를 명기해 주어야 한다.

 

다중 상속 시 멤버를 중복해지 상속하지 않고 한 번만 상속하기 위해서는 virtual 키워드를 사용하면 된다.

 

교재 p/286 클래스 - 포함 예제, 

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

class Date
{
    protected:
        int year, month, day;
    public:
        Date(int y, int m, int d)
        {
            year = y;
            month = m;
            day = d;
        }
        void OutDate()
        {
            printf("%d/%d/%d", year, month, day);
        }
};

class Product
{
    private:
        char Name[64];
        char Company[32];
        Date ValidTo;
        int Price;

    public:
        Product(const char *aN, const char *aC, int y, int m, int d, int aP)
        : ValidTo(y, m, d)
        {
            strcpy(Name, aN);
            strcpy(Company, aC);
            Price = aP;
        }

        void OutProduct()
        {
            printf("이름: %s \n", Name);
            printf("제조사: %s \n", Company);
            printf("유효기간:");
            ValidTo.OutDate();
            puts("");
            printf("가격:%d\n", Price);
        }
};

int main(void)
{
    Product S("새우깡""농심"2009,8,15,900);
    S.OutProduct();
    return 0;
}

교재 p/289 private 상속 예제,

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

class Date
{
    protected:
        int year, month, day;
    public:
        Date(int y, int m, int d)
        {
            year = y;
            month = m;
            day = d;
        }
        void OutDate()
        {
            printf("%d/%d/%d", year, month, day);
        }
};

class Product : private Date
{
    private:
        char Name[64];
        char Company[32];
        int Price;

    public:
        Product(const char *aN, const char *aC, int y, int m, int d, int aP)
        : Date(y, m, d)
        {
            strcpy(Name, aN);
            strcpy(Company, aC);
            Price = aP;
        }
        void OutProduct()
        {
            printf("이름: %s \n", Name);
            printf("제조사: %s \n", Company);
            printf("유효기간:");
            OutDate();
            puts("");
            printf("가격:%d\n", Price);
        }
};

int main(void)
{
    Product S("새우깡""농심"2009,8,15,900);
    S.OutProduct();
    return 0;
}

 

 

 

반응형
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 15. 15:51

================================ Outline ====================================

상속 

----------------------------------------------------------------------------

 

class Car

{

public:

int iNum;

};

 

class BMW : ___ Car (제한자를 선언해주지 않으면 private으로 간주한다.)

{

int iNum;

void test()

{

Car::iNum = 100; //스코프 연산자를 통해 iNum으로 이동할 수 있다.

}

};

 

 

private, protected를 활용하여 보안, 자료의 캡슐화를 할 수 있다.

 

 

부모(기반, base), 자식(상속, derived)

 

 

 

반응형
Posted by newind2000
Busan IT/제어 UI(C++)2015. 6. 12. 17:43

생성자, 소멸자, 복사생성자, 함수의 구현

이전 시간에 만들던 car.cpp의 함수를 계속해서 만들어보자. 

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

class CAR
{
    private:
        int iColor;
        int iSpeed;
        char *cName;

        void CarName(const char *);

    public:
        CAR();
        CAR(CAR &);
        CAR(const char *);
        ~CAR();
        void SetColor(int);
        void SetSpeed(int);
        void SetName(const char *);
        void Print(ostream *T);
        const CAR operator=(const CAR &);
        void operator+=(const CAR &IN);

};

CAR::CAR()
{
    CarName("CAR");
}
CAR::~CAR()
{
#ifdef debug 
    cout<<"잘있어. 나 잊지마  [ " << cName <<" ] 이야! TT-TT\n";
#endif //debug
    delete [] cName;
}
CAR::CAR(CAR& T)
{
    iColor = T.iColor;
    iSpeed = T.iSpeed;
    cName = new char[strlen("T.cName")+1];
    strcpy(cName, T.cName);
#ifdef debug 
    cout<<"안녕?  난 복사 [ " << cName <<" ]이라고 해! *'-'*\n";
#endif //debug
}

void CAR::SetColor(int iC)
{
    iColor = iC;
#ifdef debug 
    cout<< cName <<":: iColor 값이 [" << iColor << "]로 변경되었습니다.\n";
#endif //debug
}
void CAR::SetSpeed(int iS)
{
    iSpeed = iS;
#ifdef debug 
    cout<< cName <<":: iSpeed 값이 [" << iS << "]로 변경되었습니다.\n";
#endif //debug
}

void CAR::SetName(const char * cp)
{
#ifdef debug 
    cout <<"["<<cName;
#endif //debug
    delete [] cName;
    cName = new char[strlen(cp)+1];
    strcpy(cName, cp);
#ifdef debug 
    cout<<"]의 이름이 ["<<cName<<"]으로 변경되었습니다."<<endl;
#endif //debug

}

const CAR CAR::operator=(const CAR & T)
{
    SetColor(T.iColor);
    SetSpeed(T.iSpeed);
    SetName(T.cName);

    return *this;          //*this 호출하면서 복사 생성자가 만들어진다.
}
CAR::CAR(const char * T)
{
    CarName(T);
}
void CAR::CarName(const char * T)
{
    iColor = 0;
    iSpeed = 0;
    cName = new char[strlen(T)+1];
    strcpy(cName, T);

#ifdef debug 
    cout<<"안녕? 난[ " << cName <<" ]이라고 해! *'-'*\n";
#endif //debug
    
}

void CAR::operator+=(const CAR &T)
{
    iColor = iColor + T.iColor;
    iSpeed = iSpeed + T.iSpeed;

    char * cpTemp = new char [strlen(cName)+strlen(T.cName)+1];
    strcpy(cpTemp, T.cName);

    strcat(cpTemp, cName);
    delete [] cName;
    cName = cpTemp;
    cout<<cName<<endl;
}
    
void CAR::Print(ostream *T)         //ostream::차후에 cout을 인자로 받을 것이다.
{
    *T << "CAR [" << iColor << "," << iSpeed << "," << cName <<"]";
}
    
ostream& operator<<(ostream & O, CAR & T)
{

    T.Print(&O);
    return O; 
}

int main(void)
{
    CAR car1;    
    CAR car2("티코 GT 슈퍼터보");
    CAR car3("내꺼");
    car3 = car2 = car1;     //carName의 반환값은 void이기 때문에 car3는 void를 갖게 되어서 에러->반환값을 *this로 변경
    car2.operator+=(car3);
    //car3.Print(&cout);
    cout<<car3<<endl;

    return 0;
}

 

 

//realloc의 메뉴얼

 



 

car.cpp 완성!

 

ppt로 넘어가서

ch 21, p/37 - 

ch 22.


21.ppt


22.ppt


/*** cin 의 사용 ***/

#include <iostream>

using namespace std;

int main(void)
{
    char cNum;
    int iNum;
    float fNum;

    //cin >> cNum;              //char는 입력 받으면 1개만 출력해준다.
    //cout <<(int)cNum <<endl;  //때문에 int로 캐스팅

    //cin >> fNum;
    //cout <<fNum <<endl;

    char buf[200];
    cin >> buf;
    cout << buf <<endl;
    return 0;
}


/*** 상속 ***/
#include <iostream>

using namespace std;

class CAR
{
    public :
        CAR()
        {
            cout<<"CAR class가 생성되었습니다."<<endl;
        }
        ~CAR()
        {
            cout<<"CAR class가 소멸되었습니다."<<endl;

        }

};

class BMW : CAR //BMW는 CAR를 상속 받는다. Java에서는 ':' 대신에 'extends'를 사용한다.
{
    public :
        BMW()
        {
            cout<<"BMW class가 생성되었습니다."<<endl;
        }
        ~BMW()
        {
            cout<<"BMW class가 소멸되었습니다."<<endl;

        }

};
int main(void)
{
   BMW obj1; 
    return 0;
}


반응형
Posted by newind2000