티스토리 뷰

1. 생성자의 개념. (멤버함수와의 차이점도 설명되어야 함)


생성자랑 클래스를 만들때 실행되는 것이며 클래스 내부에서 선언하여 사용한다

만약 생성자를 만들지 않아도 기본적으로 기본 생성자가 실행되는데 이 기본 생정자는 

매개변수와 함수를 가지지 않는 빈 생성자이다.

생성자를 만들어 쓸경우가 있는데 이때는 새롭게 생성자를 정의 하여도 기본 생성자를 표시 해주어야 

컴파일 에러가 나지 않는다.


멤버함수와의 차이점은 생성자는 클래스가 생성될때 한번 실행되는것이고 멤버 함수는 생성된 클래스에서 필요할때마다 호출하여 사용할수 있다는 점이 차이점이다.


생성자의 예시이다.

class Rectangle{

      public:

      int height;

      int width;

      Rectangle();

};


생성자는 항상 public 으로 정의하여야하는데 왜냐하면 생성자는 다른 클래스에서 접근을 하지못하면 클래스 자체가 생성 되지 않기 때문이다.

Rectangle:: Rectangle(){

            height = 1;

            width =1;

}

아래는 생성자의 몸체이다 위 예제는 height,width 변수를 객체가 만들어질때 1로 정의한다는 예제이다.


2. 생성자 예제

Rectangle 클래스 예제이다.


#include <iostream>


using namespace std;


class Rectangle{

      public:

      int height;

      int width;

      Rectangle();

      Rectangle(int h);

      Rectangle(int h, int w);

      bool isSquare();

};


Rectangle:: Rectangle(){

            height = 1;

            width =1;

}


Rectangle:: Rectangle(int h){

            height = h;

            width = h;

}


Rectangle:: Rectangle(int h, int w){

            height = h;

            width = w;

}


bool Rectangle:: isSquare(){

     if(height == width) 

     return true;

     else return false;

}


int main(int argc, char *argv[])

{

    Rectangle rect1;

    Rectangle rect2(5);

    Rectangle rect3(3,5);

    

    if(rect1.isSquare()) cout << "rect1은 정사각형이다 "<<endl; 

    if(rect2.isSquare()) cout << "rect2은 정사각형이다 "<<endl;

    if(rect3.isSquare()) cout << "rect3은 정사각형이다 "<<endl;


    system("PAUSE");

    return EXIT_SUCCESS;

}






3. 소멸자 특징


소멸자란 C++ 가 가지는 특징 중에 하나이다.

C++는 자바와 달리 메모리를 사용자가 직접 관리를 해줘야 한다는 특징이 있다.

자바 같은경우 가비지 커넥션이라고 JVM에서 생성한 객체들이 더이상 연결이 되어 있지 않다면 JVM자체에서 객체를 가비지로 인식하여 메모리상에서 제거한다,

하지만 C++ 에서는 이러한 기능이 구현되어 있지 않아 사용자가 일일이 메모리를 관리해 주어야한다는 특징이 있다.



4. 소멸자 예제


아래예제는 프로그램이 종료될때 지금까지 만든 Circle 객체를 제거하는 예제 인데 출력결과를 보고 이야기 하겠습니다.



#include <cstdlib>

#include <iostream>


using namespace std;


class Circle{

      public:

             int radius;

             Circle();

             Circle(int r);

             ~Circle(); // 소멸자 생성

             double getArea();

};

Circle:: Circle(){

      radius = 1;

      cout << "반지름"<<radius<<"원 생성"<<endl;

}


Circle::Circle(int r){

      radius = r;

      cout << "반지름"<<radius<<"원 생성"<<endl;  

}


Circle:: ~Circle(){ //소멸자 실행

         cout << "반지름"<<radius<< " 원 소멸"<<endl;

         system("PAUSE");

}


double Circle::getArea(){

       return 3.14*radius*radius;

}


Circle globalDonut(1000);

Circle globalPizza(2000);


void f(){

     Circle fDonut(100);

     Circle fPizza(200);

}

int main(int argc, char *argv[])

{

    

    Circle mainDonut;

 

    Circle mainPizza(30);

       f();

    system("PAUSE");

    return EXIT_SUCCESS;

    

}


출력결과




위 결과를 보시면 생성한 순서의 반대로 소멸되는것을 알수 있습니다.

이러한 자료구조를 스택 (Last in First Out) 이라고 합니다.



5. [응용] 계산기 프로그램


소스코드 입니다.


#include <cstdlib>

#include <iostream>


using namespace std;


class Calculator{

      public:

             void run();

};


class Adder{

      int op1,op2;

      public:

             Adder(int a, int b);

 ~Adder();

             int process();

};


class Sub{

      int op1, op2;

      public:

             Sub(int a, int b);

             ~Sub();

 int process();

};


class Multi{

      int op1, op2;

      public:

             Multi(int a, int b);

 ~Multi();

             int process();

};


class Divide{

      int op1, op2;

      public: 

              Divide(int a, int b);

  ~Divide();

              int process();

};


Adder:: Adder(int a, int b){

        op1 = a;

        op2 = b;

}


int Adder:: process(){

    return op1 + op2;

}            


Sub:: Sub(int a, int b){

    op1 = a;

    op2 = b;

}

int Sub:: process(){

    return op1 - op2;

}


Multi:: Multi(int a, int b){

      op1 = a;

      op2 = b;

}


int Multi :: process(){

    return op1*op2;

}


Divide:: Divide(int a, int b){

       op1 = a;

       op2 = b;

}


int Divide:: process(){

    return op1%op2;

}


void Calculator:: run(){

     cout << "두 개의 수와 연산기호를 입력하세요>>";

     int a,b;

     char c;

     cin >>a>>b>>c;

     switch(c){

               case '+':{

                    Adder adder(a,b);

                    cout << adder.process() << endl;

                    break;

                    }

              case '-':{

                    Sub sub(a,b);

                    cout << sub.process() << endl;

                    break;

                    }

               case '*':{

                    Multi multi(a,b);

                    cout << multi.process() << endl;

                    break;

                    }

               case '/':{

                    Divide divide(a,b);

                    cout << divide.process() << endl;

                    break;

                    }

               defalut: break;

                    }

}


int main(int argc, char *argv[])

{

    Calculator calc;

    calc.run(); 

    system("PAUSE");

    return EXIT_SUCCESS;

    

}


실행결과 입니다





'IT > C++' 카테고리의 다른 글

[C++] 배열과 객체의 동적 할당  (2) 2014.10.29
[C++] 계산기 예제  (0) 2014.10.08
통장관리프로그램  (2) 2014.09.26
[C++] BankAccount 예제  (0) 2014.09.25
[C++] 예제 3  (0) 2014.09.25
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함