본문 바로가기

프로그램언어/C++

클래스1

 

클래스란?

클래스를 한마디로 설명하면 사용자 자신의 타입을 만들 수 있는 타입 생성기라고 할 수 있다.

 

클래스 구조

클래스는 구성적인 측면에서 볼 때 자료구조를 타나내는 데이터 멤버와 인터페이스를 나타내는 멤버 함수로 나눌 수 있다. 객체지향 용어를 빌리자면 데이터 멤버는 인스턴스 변수라 하고 멤버 함수는 객체에 보내는 메시지를 타나내는 메서드라 부른다.

 

클래스 선언

- 클래스 선언은 클래스 명세라고도 하며 예약어 class와 사용자 타입 이름을 적은 다음 몸통부를 중괄호({ })를 사용하여 묶는다. 다든 중괄호(}) 뒤엔 세미콜론(;)이 있어야 한다. 중괄호 사이에는 접근 권한에 대한 예약어(public, private, protected)를 사용할 수 있다. 접근 권한 예약어 뒤엔 콜론(:)을 붙여 명시한다. 중괄호 사이에는 공개, 비공개, 보호영역이 존재할 수 있으며, 영역에 따른 다음과 같이 구분할 수 있다. 각 영역은 데이터 멤버와 멤버 함수를 가질 수 있다. 멤버 함수는 명세 내부에서 직접 정의 할 수도 있고 또 클래스 명세 내부에서 함수 원형만 선언하고 클래스 명세 밖에서 정의할 수도 있다.

 

 

class 클래스명
{
    멤버 변수;

접근지정자:
    멤버 함수();
};

클래스명::멤버 함수() {
    명령어 처리
}
class 클래스명 {
private:
    멤버 변수;

public:
    멤버 함수();
};

클래스명::멤버 함수() {
    명령어 처리
}

클래스명::

- 콜론콜론 연산자(::)는 클래스 범위를 지정하는 연산자이다. 즉 이 함수는 클래스에 묶인 함수임을 나타낸다.

 

접근지정자 종류

- public 접근지정자 : 공개 영역

- private 접근지정자 : 비공개 영역

- protected 접근지정자 : 보호 영역

 

 

예1] 예2]
class Date
{
    int m_year;
    int m_month;  
    int m_day;

};
class Date
{
private:     // 비공개 영역, 생략 가능
    int m_year;
    int m_month;
    int m_day;
};

 

"예1]"은 접근 권한 예약어를 사용하지 않았습니다. 클래스는 기본적으로 비공개 접근 권한을 가진다. private 예약어를 사용한 것과 같습니다. 클래스의 인스턴스 변수는 대개 사용자가 직접 건드리지 않도록 하므로 비공개 부분에 넣어야 한다.

 

class Date
{
//비공개 데이터 멤버
    ....
 
public: //공개 영역
    void setDate(int year, int month, int day);   // 날짜 설정
    int getYear();      //년 반환
    int getMonth();   //월 반환

    int getDay();       //일 반환
    void print();        // 날짜 출력
};

데이터 멤버 변수를 선언한 다음 멤버 함수를 선언합니다. 클래스 내부적으로 사용할 것이라면 비공개 영역에 두고, 아니면 공개 영역에 두어서 클래스 사용자가 접근할 수 있도록 제공합니다. 멤버 함수는 클래스의 데이터 멤버 변수에 접근하여 연산을 합니다. 데이터 접근은 추상적으로 데이터를 읽거나 데이터를 쓰는 연산을 말합니다. 즉 멤버 함수는 데이터 멤버 변수의 현재 상태 값을 읽어오거나 데이터 멤버 변수의 상태를 변경시키는 연산으로 크게 나누어진니다. 여기에서는 날짜를 설정하는 함수 setDate()와 날짜의 멤버를 읽는 getYear(), getMonth, getDay(), 그리고 날짜를 출력시키는print()함수를 제공하고 있습니다. 이들 멤버 함수는 클래스 사용자에게 모두 필요한 연산이므로 공개 영역에 두기 위해 public을 선언하고 아래에 멤버 함수를 작성하였습니다.

 

클래스 멤버함수 작성하기

void Date::setDate(int year, int month, int day)
{
    m_year = year;
    m_month = month;
    m_day = day;
}


int Date::getYear()
{
    return m_year;
}
 
int Date::getMonth()
{
    return m_month;
}
 
int Date::getDay()
{
    return m_day;
}


void Date::print()
{
    cut << m_year << "“ << m_month << "” << m_day << "“;
}

 

클래스 실행하기

void main()
{
    Date today;
    today.setDate(2020, 8 ,5);
 
    int year = today.getYear();
    int month = today.getMonth();
    int day = today.getDay();
 
    cout << "오늘은 단기 " << year + 2333 << "" << month << "" <<day << "일 입니다." << endl;
    cout << "오늘은 서기 ";
    today.print();
    cout <<
" 입니다." << endl;

}
실행 결과
오늘은 단기 4353년 8월 5일 입니다.
오늘은 서기 2020년8월5일 입니다.

 

전체코드

#include<iostream>
using namespace std;
 
class Date
{
    int m_year;
    int m_month;
    int m_day;
public: //공개 영역
    void setDate(int year, int month, int day);
    int getYear(); //년 반환
    int getMonth(); //월 반환
    int getDay(); //일 반환
    void print(); // 날짜 출력
};


void Date::setDate(int year, int month, int day)
{
    m_year = year;
    m_month = month;
    m_day = day;
}
 
int Date::getYear()
{
    return m_year;
}
 
int Date::getMonth()
{
    return m_month;
}
 
int Date::getDay()
{
    return m_day;
}
 
void Date::print()
{
    cout << m_year << "" << m_month << "" << m_day << "";
}
 
int main()
{
    Date today;
    today.setDate(2020, 8, 5);
 
    int year = today.getYear();
    int month = today.getMonth();
    int day = today.getDay();
 
    cout << "오늘은 단기 " << year + 2333 << "" << month << "" << day << "일 입니다." << endl;
    cout << "오늘은 서기 ";
    today.print();
    cout << " 입니다." << endl;
 
    return 0;
}

 

멤버 변수

클래스 내에서 선언된 변수를 멤버 변수라 한다. 멤버 변수는 실제 오브젝트를 구성하는 각각의 기억공간을 말하며 처리시과정에서 데이터를 담아둘 목적으로 사용한다. 클래스 내에 있는 멤버함수 속에서 단순히 멤버 변수 이름만으로 사용할 수 있으나 클래스 자료형 외부에서 지칭 할 경우에는 바드시 오브젝트이름 뒤에 점( . )연산자를 기재한 후에 멤버 변수 이름을 입력해야 한다.

 

 

멤버 함수

클래스의 구성원으로 만어진 함수이다.

멤버 함수는 클래스 선언시 클래스 안에서 함수와 함수의 몸체를 모두 기재하는 방법이 있고 클래스 안에서는 함수의 원형만 선언하고 실제 멤버 함수의 내용은 클래스 선언부 밖에서 기재하는 방법도 있다.

멤버 함수들도 접근 지정자를 입력하여 사용하며 주로 멤버 함수들은 접근 지정자를 public으로 많이 지정한다.  그 이유는 외부에서 멤버 함수를 통해 멤버 변수에 접근하기 때문이다.

 

 

접근 지정자의 종류

public : 멤버변수나 멤버함수가 public으로 선언되면 클래스 내부뿐만 아니라 외부에서도 접근이 가능하다.

private : 멤버변수나 멤버함수가 private로 선언되면 클래스 내의 멤버함수 속에서만 사용할 수 있다. (단 friend로 지정된 함수와 friend로 지정된 클래스에서는 private으로 지정된 멤버에도 접근할 수 있다.)

protected : 멤버변수나 멤버함수가 protected로 선언되면 해당 멤버들은 자신의 클래스내의 멤버함수와 서브 클래스 내의 멤버함수 속에서 사용할 수 있다.

 

#include<iostream>
using namespace std;
 
class sungjuk
{
public:
    int kor;
    int eng;
};
  
int main()
{
    sungjuk test;
    test.kor = 90;
    test.eng = 80;
 
    cout << "국어점수 : " << test.kor;
    cout << "
영어점수 : " << test.eng << endl;

 
    return 0;
}
#include<iostream>
using namespace std;
 
class sungjuk
{
private:
    int total;

public:
    int kor;
    int eng;
    void sum();

};
void sungjuk::sum()
{
    total = kor + eng;
    cout << "총점 : " << total << endl;
}

int main()
{
    sungjuk test;
    test.kor = 90;
    test.eng = 80;
 
    cout << "국어점수 : " << test.kor;
    cout << " 
영어점수 : " << test.eng << endl;

    // test.total = test.kor + test.eng;   // 에러발생
    test.sum();

    return 0;
}
국어점수 : 90 영어점수 : 80 국어점수 : 90 영어점수 : 80
총점 : 170

 

#include<iostream>
using namespace std;
 
class sungjuk
{
private:
    int kor;
    int eng;
public:
    void setK(int k);
    void setE(int e);
    void disp();
};
void sungjuk::setK(int k)
{
    kor = k;
}
void sungjuk::setE(int e)
{
    eng = e;
}
void sungjuk::disp()
{
    cout << "국어점수 : " << kor;
    cout << " 영어점수 : " << eng << endl;
}


int main()
{
    sungjuk test;
    test.setK(90);
    test.setE(80);
 
    test.disp();


    return 0;
}
#include<iostream>
using namespace std;
 
class sungjuk
{
private:
    int total;
    int kor;
    int eng;
public:
    void setK(int k);
    void setE(int e);
    void disp();
    void sum();
};
void sungjuk::setK(int k)
{
    kor = k;
}
void sungjuk::setE(int e)
{
    eng = e;
}
void sungjuk::disp()
{
    cout << "국어점수 : " << kor;
    cout << " 영어점수 : " << eng << endl;
}

void sungjuk::sum()
{
    total = kor + eng;
    cout << "총점 : " << total << endl;
}
 
int main()
{
    sungjuk test;
    test.setK(90);
    test.setE(80);
    test.disp();
    test.sum();
    return 0;
}
국어점수 : 90 영어점수 : 80  국어점수 : 90 영어점수 : 80 
총점 : 170

 

#include<iostream>
#include<cstring>
using namespace std;
 
class sungjuk
{
private:
    int num;
    char *name;
public:
    void setNum(int n);
    void setName(char *s);
    void disp();
};
void sungjuk::setNum(int n)
{
    num = n;
}
void sungjuk::setName(char* s)
{
    name = new char[strlen(s) + 1];
    strcpy(name, s);
}
 
void sungjuk::disp()
{
cout << "번호 : " << num;
cout << " 이름 : " << name << endl;
}
 
int main()
{
    sungjuk test;
    char arr[20] = "학생1";
    test.setNum(100);
    test.setName(arr);
    test.disp();
 
    return 0;
}
실행 결과
번호 : 100 이름 : 학생1

 

함수오버로드

클래스안에서 동일한 이름의 멤버 함수가 2개 이상 존재하는 것을 오버로드 멤버함수라 한다.

#include <iostream>
#include <cstring>
using namespace std;
 
class student
{
    char name[10];
    int age;
public:
    void set(const char *s);
    void set(int n);
    void set(const char* s, int n);
    void disp();
};
 
void student::set(const char* s)
{
    strcpy_s(name, s);
}
void student::set(int n)
{
    age = n;
}
void student::set(const char* s, int n)
{
    strcpy_s(name, s);
    age = n;
}
 
void student::disp()
{
  cout << "이름 : " << name << " 나이 : " << age << endl;
}
int main()
{
    student stu;
    stu.set("학생1");
    stu.set(19);
    stu.disp();
 
    student stu2;
    stu2.set("학생2", 20);
    stu2.disp();
 
    return 0;
}
실행 결과
이름 : 학생1 나이 : 19
이름 : 학생2 나이 : 20

 

인라인 멤버함수

클래스 안에서 멤버함수을 몸체와 함께 작성하면 해당 멤버함수는 기본적으로 인라인 함수로 취급하게 된다.

클래스 안에서 멤버함수의 프로토타입만 기재하고 실제 멤버함수의 내용을 클래스 밖에서 작성하면서 그 멤버함수를 인라인 함수로 만들려면 함수명 앞에 inline이라는 키워드를 입력하면 된다.

 

#include <iostream>
#include <cstring>
 
using namespace std;
 
class student
{
    char name[10];
    int age;
public:
    void set(const char* s) // 인라인 함수
    {
        strcpy_s(name, s);
    }
     void set(int n);
    void set(const char* s, int n);
    void disp();
};
 
inline void student::set(int n)
{
    age = n;
}
 
inline void student::set(const char* s, int n)
{
    strcpy_s(name, s);
    age = n;
}
 
inline void student::disp()
{
  cout << "이름 : " << name << " 나이 : " << age << endl;
}
 
int main()
{
    student stu;
    stu.set("학생1");
    stu.set(19);
    stu.disp();
 
    student stu2;
    stu2.set("학생2", 20);
    stu2.disp();
 
return 0;
}
실행 결과
이름 : 학생1 나이 : 19
이름 : 학생2 나이 : 20

 

const 멤버함수

멤버함수 뒤에 const라는 예약어가 기재된 멤버함수를 const멤버함수라고 한다.

const 멤버 함수로 선언하게 되면 그 멤버함수 속에서는 멤버변수의 값을 이용만 할 수 있고 변경하는 것은 불가능하게 된다.

 

- const 오브젝트를 이용하여 일반멤버함수를 호출해서는 안 된다. 만일 호출하려 할 경우에는 컴파일러가 경고 메시지를 발생시킨다.

- const 오브젝트는 const형 멤버함수만을 호출하는 것을 원칙으로 한다.

 

 

#include <iostream>
#include <cstring>
 
using namespace std;
 
class student
{
    char name[10];
    int age;
public:
    void set(const char* s);
    void set(int n);
    void set(const char* s, int n);
    void disp() const;
};
void student::set(const char* s)
{
    strcpy_s(name, s);
}
 
void student::set(int n)
{
    age = n;
}
 
void student::set(const char* s, int n)
{
    strcpy_s(name, s);
    age = n;
}
 
void student::disp() const
{
  cout << "이름 : " << name << " 나이 : " << age << endl;
}
 
int main()
{
    student stu;
    stu.set("학생1");
    stu.set(19);
    stu.disp();
 
    student stu2;
    stu2.set("학생2", 20);
    stu2.disp();
 
    return 0;
}
실행 결과
이름 : 학생1 나이 : 19
이름 : 학생2 나이 : 20

'프로그램언어 > C++' 카테고리의 다른 글

클래스3  (0) 2020.08.07
클래스2 문제  (0) 2020.08.07
클래스2  (0) 2020.08.06
클래스1 - 문제  (0) 2020.08.06
C++ 시작하기  (0) 2019.10.22