C++ 7.생성자와 소멸자

-생성자와 소멸자

 

//Student.h

#pragma once

#include <iostream>

#include <string>

using namespace std;

 

class Student

{

        int num;

        string name;

public:

        Student(void);

        Student(int num);

        Student(int num, string name);

        void View();

};

 

//Student.h

#include "Student.h"

 

Student::Student(void)

{

        num = 0;

        name = "";

}

 

Student::Student(int _num)

{

        num = _num;

        name = "";

}

 

Student::Student(int _num, string _name)

{

        num = _num;

        name = _name;

}

 

void Student::View()

{

        if(num)

        {

               cout<<"번호 :"<<num;

        }

        else

        {

               cout<<"번호 : N/A";

        }

        if(name != "")

        {

               cout<<"이름 :"<<name<<endl;

        }

        else

        {

               cout<<"이름 :NA"<<endl;

        }

}

 

 

//Program

#include "Student.h"

 

int main(void)

{

        Student *stu1 = new Student();

        Student *stu2 = new Student(3);

        Student *stu3 = new Student(3,"홍길동");

 

        Student s1(2,"홍길동");

        Student s2(s1); //복사생성자

        Student *s3 = new Student(3,"강감찬");

        Student *s4 = new Student(*s3); //복사생성자

 

        stu1->View();

        stu2->View();

        stu3->View();

 

        s1.View();

        s2.View();

        s3->View();

        s4->View();

 

        delete stu1;

        delete stu2;

        delete stu3;

        delete s3;

        delete s4;

 

        return 0;

}

 

 

728x90

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

C++ 10.캡슐화 실습(복소수)  (0) 2016.04.19
C++ 9.복사 생성자  (0) 2016.04.19
C++ 6.접근 지정자  (0) 2016.04.19
C++ 5.정적 클래스  (0) 2016.04.19
C++ 4.정적멤버 static  (0) 2016.04.19

이 글을 공유하기

댓글

Designed by JB FACTORY