티스토리 뷰

1. 클래스, 객체

(1) 클래스

클래스란 객체를 정의하는 틀이라고 할 수 있습니다.

클래스는 멤버변수와 멤버 함수 두 종류를 가지고 있으며

멤버변수에는 데이터 즉 상태를 저장하고 멤버 함수에서는 속성을 변경하거나 연산을 수행하여 값을 반환하는 행동을 합니다.



(2) 객체의 특징

객체는 자신만의 고유한 상태와 행동으로 구성이됩니다.

행동으로 상태가 변화하는데 행동이란 클래스에서 말한 멤버 함수를 의미하며 상태란 멤버변수를 의미합니다.

객체란 상태와 행동 즉 멤버 변수와 멤버 함수로 이루어진 것을 의미합니다.


2. 클래스 작성 방법

- C++에서의 클래스 작성 방법은 Java와는 다소 차이가 있습니다.

  C++에서 클래스 작성하기 위해서는 클래스 선언부와 클래스 구현부로 나누어져 있습니다.

  클래스 선언부에서는 멤버 변수나 함수를 정의하고 클래스 구현부에서 실제로 사용 될 클래스의 함수를 구현하는 역할을 담당합니다.

  클래스의 선언부에는 필수적으로 ; 세미콜론을 붙여야 합니다.

- C++에서는 접근 지정자를 아래와 같이 한번에 표기합니다.

  int radius; 와 double getARea();는 public 으로 지정되었습니다.


1
2
3
4
5
6
7
8
9
class Circle {  //클래스 선언부
public:
   int radius;
   double getArea();
};
 
double Circle::getArea() {  //클래스 구현부
   return 3.14*radius*radius;
}
cs


3. 객체 생성 방법

(donut, pizza, cake 생성예제 코드, 실행결과)


예제코드

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
32
33
34
35
#include <cstdlib>
#include <iostream>
using namespace std;
 
class Circle {
public:
       int radius;
       double getArea();
       void setArea(int num);
};
 
double Circle:: getArea() {
       return 3.14 * radius * radius;
}
 
void Circle:: setArea(int num) {
     radius = num;
}
 
int main()
{
    Circle donut;
    Circle pizza;
    Circle cake;
    
    donut.setArea(1);
    pizza.setArea(30);
    cake.setArea(20);
    
    cout << "도넛의 면적은 " << donut.getArea() << "입니다." << endl;
    cout << "피자의 면적은 " << pizza.getArea() << "입니다." << endl;
    cout << "케이크의 면적은 " << cake.getArea() << "입니다." << endl;
    
    system("PAUSE");
cs


실행결과





4. main()에서 객체의 멤버변수, 함수 접근방법설명

- main()에서 객체의 멤버 변수나 함수에 접근하기 위해서는 먼저 객체를 생성해야 합니다.

  위에서 클래스를 선언했다고해서 메모리에 객체가 생성된 것은 아니기 때문에 객체를 생성해 주어야 하는데\

  이는     클래스이름 객체이름;    으로 객체를 생성해 줄 수 있습니다.

  이렇게 생성한 객체이름에 .을 붙여 멤버 변수나 멤버 함수에 접근할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
int main() {
   Circle donut;   // 객체 생성
 
   donut.radius = 1;   // 객체의 멤버 변수에 접근
   double area = donut.getArea();   // 객체의 멤버 함수에 접근
 
   cout << "도넛의 면적은 " << donut.getArea() << "입니다." << endl;
 
   system("PAUSE");
}
cs



5. Rectangle 클래스 만들기 예제완성(소스코드, 실행결과)


예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cstdlib>
#include <iostream>
using namespace std;
 
class Rectangle {
public:
       int width;
       int height;
       int getArea();
};
 
intx Rectangle:: getArea() {
       return width * height;
}
int main()
{
    Rectangle rect;
    rect.width = 3;
    rect.height = 5;
    cout << "사각형의 면적은 " << rect.getArea() << endl;
    
    system("PAUSE");
}
 
cs


실행결과


6. BankAccount 예제

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <cstdlib>
 
using namespace std;
 
class BankAccount {
private// 클래스 멤버 변수를 private로 선언
    int accountNumber;
    string owner;
    int balance;
 
public// 클래스 멤버 함수를 public으로 선언
    // 클래스 멤버 변수를 반환하는 함수
    int getAccountNumber();
    string getOwner();
    int getBalance();
 
    // 클래스 멤버 변수를 변경하는 함수
    void setAccountNumber(int maccountNumber);
    void setOwner(string mowner);
    void setBalance(int mbalance);
 
    // balance의 값을 변경하는 함수
    void deposti(int mbalance);
    void withdraw(int mbalance);
};
 
int BankAccount::getAccountNumber() { // accountNumber를 반환
    return accountNumber;
}
 
string BankAccount::getOwner() { // owner를 반환
    return owner;
}
 
int BankAccount::getBalance() { // balance를 반환
    return balance;
}
 
void BankAccount::setAccountNumber(int maccountNumber) { // accountNumber를 변경하는 함수
    accountNumber = maccountNumber;
}
 
void BankAccount::setOwner(string mowner) { // owner를 변경하는 함수
    owner = mowner;
}
 
void BankAccount::setBalance(int mbalance) { // balance를 변경하는 함수
    balance = mbalance;
}
 
void BankAccount::deposti(int mbalance) { // balance에 파라미터로 입력한 값만큼 더한다.
    balance += mbalance;
}
 
void BankAccount::withdraw(int mbalance) { // balance에 파라미터로 입력한 값만큼 감소시킨다.
    balance -= mbalance;
}
 
int main(int argc, char** argv) {
    // BankAccount 객체 생성
    BankAccount account;
 
    // balance의 값을 0으로 초기화
    account.setBalance(0);
 
    // balance에 10000을 더한다.
    account.deposti(10000);
 
    // balance의 값을 출력한다.
    cout << "잔액은: " << account.getBalance() << endl;
 
    // balance에 2000을 감소시킨다.
    account.withdraw(2000);
 
    // balance의 값을 출력한다.
    cout << "잔액은: " << account.getBalance() << endl;
 
    return 0;
}
cs

출력결과



7. BankAccount 헤어 파일과 cpp 파일로 분리


a) BankAccount 헤더파일의 선언부를 헤더파일로 분리한다.

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
class BankAccount {
private// 클래스 멤버 변수를 private로 선언
    int accountNumber;
    string owner;
    int balance;
 
public// 클래스 멤버 함수를 public으로 선언
    // 클래스 멤버 변수를 반환하는 함수
    int getAccountNumber();
    string getOwner();
    int getBalance();
 
    // 클래스 멤버 변수를 변경하는 함수
    void setAccountNumber(int maccountNumber);
    void setOwner(string mowner);
    void setBalance(int mbalance);
 
    // balance의 값을 변경하는 함수
    void deposti(int mbalance);
    void withdraw(int mbalance);
    
    //잔액 초기화 
    void initBalance();
    void print();
};
cs

b) 클래스의 몸체 부분을 cpp 파일로 분리한다.

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
32
33
34
35
36
37
38
#include <iostream>
 
using namespace std;
#include "BankAccount.h"
int BankAccount::getAccountNumber() { // accountNumber를 반환
    return accountNumber;
}
 
string BankAccount::getOwner() { // owner를 반환
    return owner;
}
 
int BankAccount::getBalance() { // balance를 반환
    return balance;
}
 
void BankAccount::setAccountNumber(int maccountNumber) { // accountNumber를 변경하는 함수
    accountNumber = maccountNumber;
}
 
void BankAccount::setOwner(string mowner) { // owner를 변경하는 함수
    owner = mowner;
}
 
void BankAccount::setBalance(int mbalance) { // balance를 변경하는 함수
    balance = mbalance;
}
 
void BankAccount::deposti(int mbalance) { // balance에 파라미터로 입력한 값만큼 더한다.
    balance += mbalance;
}
 
void BankAccount::withdraw(int mbalance) { // balance에 파라미터로 입력한 값만큼 감소시킨다.
    balance -= mbalance;
}
void BankAccount::initBalance() {
    balance = 0;
}

void BankAccount::print() {
// BankAccount의 멤버 함수에서는 BankAccount의 멤버 변수에 접근 가능 
    cout << "잔액은: " << balance << endl;
}
 
cs


c) using namespace std; 코드 아랫 부분에 include를 이용하여 헤더를 추가한다.

   이렇게 추가하는 이유는 개발 툴에 따라 에러가 발생하기 때문이다.

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
#include <iostream>
 
using namespace std;
#include "BankAccount.h"
 
int main(int argc, char** argv) {
    BankAccount account;
    account.initBalance();
// balance의 값을 10000 증가 
    account.deposti(10000);
// 잔액 출력 
     account.print();
 
// balance의 값을 2000 감소 
    account.withdraw(2000);
// 잔액 출력 
     account.print();
 
    return 0;
}
cs



3.4 생성자


1. 생성자의 특징

- 객체가 생성될 때 자동으로 실행되는 특별한 멤버 함수로서 객체가 생성될 때 단 한번만 실행이 됩니다.

  또한 생성자는 객체가 생성될 때 필요한 초기 작업을 하기 위해 사용되며 클래스의 이름과 동일하게 작성되어야 합니다.

  그리고 생성자에는 리턴타입을 선언하지 않습니다.



2. 기본생성자란?

- 기본 생성자란 매개변수가 따로 존재하지 않는 생성자를 의미합니다.

  디폴트 생성자라고 부르기도 합니다.

  생성자를 하나도 선언하지 않는 경우 컴파일러는 아무런 코드도 들어있지 않는 기본 생성자를 코드에 삽입하여 줍니다.


3. 기본생성자가 자동으로 생성되는 경우

- 생성자가 하나도 없는 경우에 컴파일러는 보이지 않는 기본 생성자를 생성해줍니다.


4. 기본생성자가 자동으로 생성되지 않는 경우

- 선언된 생성자가 하나라도 존재하는 클래스의 경우 기본 생성자를 자동으로 생성하지 않습니다.


5. 생성자가 여러개인 경우의 예(예제 3-4) 소스코드, 실행결과, 주석

소스코드(주석)

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
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <cstdlib>
 
using namespace std;
 
class Rectangle {
public:
    int width, height; // Rectangle의 가로 세로 길이
    Rectangle(); // Rectangle의 기본 생성자
    Rectangle(int w, int h); // 파라미터가 두개인 Rectangle 생성자
    Rectangle(int length); // 파라미터가 한개인 Rectangle 생성자
    bool isSquare(); // Rectangle이 정사각형인지를 판별하는 멤버 함수
};
 
Rectangle::Rectangle() {
    width = height = 1// 가로 세로를 1로 초기화
}
 
Rectangle::Rectangle(int w, int h) {
    width = w; // 입력한 값으로 가로를 초기화
    height = h; // 입력한 값으로 세로를 초기화
}
 
Rectangle::Rectangle(int length) {
    width = height = length; // 입력한 값으로 가로,세로를 초기화
}
 
bool Rectangle::isSquare() { // Rectangle이 정사각형인지를 판별하는 멤버 함수
    if (width == height) return true;
    else return false;
}
 
int main() {
    Rectangle rect1; // Rectangle의 기본생성자로 생성
    Rectangle rect2(35); // 파라미터가 두개인 Rectangle 생성자로 생성
    Rectangle rect3(3); // 파라미터가 한개인 Rectangle 생성자로 생성
 
    if(rect1.isSquare()) cout << "rect1은 정사각형이다."  << endl// rect1이 정사각형이면 cout 출력
    if(rect2.isSquare()) cout << "rect2은 정사각형이다."  << endl// rect2이 정사각형이면 cout 출력
    if(rect3.isSquare()) cout << "rect3은 정사각형이다."  << endl// rect3이 정사각형이면 cout 출력
 
    return 0;
}
cs


실행결과


3.5 소멸자


1. 소멸자의 특징

- 소멸자는 객체가 사라질 때 필요한 마무리 작업을 수행합니다.

- 소멸자의 이름은 클래스의 이름 앞에 ~ 물결 표시를 붙이면 됩니다.

- 소멸자에는 반환 자료형이 존재하지 않습니다. 즉 어떠한 값도 리턴해서는 안됩니다.

- 소멸자는 오직 하나만 존재하며 매개 변수(파라미터)를 가지지 않습니다.

- 소멸자를 선언하지 않을 경우 기본 소멸자가 자동으로 생성됩니다. 기본소멸자는 아무 일도 하지 않고 단순 리턴만을 수행합니다.


2. 생성자와 소멸자의 작성 및 실행 예(프로그램 3-5 소스코드, 주석, 실행결과)

소스코드(주석)

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
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>
using namespace std;
 
class Circle {             // 클래스의 선언부 
public:
       int radius;        // 반지름 값을 저장할 클래스 멤버 변수 radius 선언 
      
      Circle();           // Circle의 기본 생성자 
      Circle(int r);      // 매개변수 하나를 가지는 생성자 
      ~Circle();          // Circle의 소멸자 
      double getArea();   // 원 넓이를 구하는 함수 
};
 
Circle::Circle() {
                 radius = 1;
                 cout << "반지름 " << radius << " 원 생성" << endl;
}
 
Circle::Circle(int r) {
                   radius = r;
                 cout << "반지름 " << radius << " 원 생성" << endl;
}
 
Circle::~Circle() {
                  cout << "반지름 " << radius << " 원 소멸" << endl;
}
 
double Circle::getArea() {
       return 3.14*radius*radius;
}
 
int main() {
    Circle donut;                 // 반지름 1 으로 원 생성 
    Circle pizza(30);             // 반지름 30 으로 원 생성
    system("pause");
    return 0;
}
 
cs


실행결과



3.7 인라인 함수


1. 소멸자의 특징

- 짧은 코드로 구성된 함수를 램의 실행속도 저하를 막기 위해 C++에서 도입된 방법입니다.

- 인라인 함수는 함수 앞에 inline 키워드를 이용하여 선언합니다.

- 컴파일러는 작은 함수에 대하여 inline 선언이 없어도 인라인 함수로 자동 처리합니다.

- 인라인 함수의 장점으로는 C++ 프로그램의 실행속도를 향상시킬 수 있다는 장점이 있으나 그 만큼 전체 크기가 늘어난다는 단점또한 있습니다.



2. 생성자와 소멸자의 작성 및 실행 예(프로그램 3-5 소스코드, 주석, 실행결과)

소스코드(주석)

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
32
33
34
35
36
#include <iostream>
#include <cstdlib>
using namespace std;
 
class Circle {             // 클래스의 선언부 
public:
       int radius;        // 반지름 값을 저장할 클래스 멤버 변수 radius 선언 
      
      Circle();           // Circle의 기본 생성자 
      Circle(int r);      // 매개변수 하나를 가지는 생성자 
      double getArea();   // 원 넓이를 구하는 함수 
};
 
inline Circle::Circle() {       // 파라미터가 없는 생성자를 인라인 함수로 선언 
                 radius = 1;
                 cout << "반지름 " << radius << " 원 생성" << endl;
}
 
Circle::Circle(int r) {
                   radius = r;
                 cout << "반지름 " << radius << " 원 생성" << endl;
}
 
inline  double Circle::getArea() {           // getArea() 함수를 인라인 함수로 선언 
       return 3.14*radius*radius;
}
 
int main() {
    Circle donut;                 // 반지름 1 으로 원 생성 
    Circle pizza(30);             // 반지름 30 으로 원 생성
    cout << "도넛의 넓이 " << donut.getArea() << endl;
    cout << "피자의 넓이 " << pizza.getArea() << endl;
    system("pause"); 
    return 0;
}
 
cs


실행결과


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   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
글 보관함