티스토리 뷰

*헤더 파일(*.h)

헤더파일의 중복을 막기 위한 처리

1
2
3
#ifndef ..._H
#define
#endif ..._H
cs


*class

class의 중요 속성 - 

Data Hiding(접근 제한자)

Encapsulation(=>data hiding)

inheritance

Pholymophism(같은 명령어, 다른 방식의 수행) - 오버라이딩


*생성자, 오버로딩, 복사생정사

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
class Point {
public:
    int x, y;
    void Print();
    Point();
    Point(int initialX, int initialY);
    Point(const Point& pt);
};
Point::Point()
{
    x = 0;
    y = 0;
}
Point::Point(int initialX, int initialY)
{
    x = initialX;
    y = initialY;
}
Point::Point(const Point & pt) // or Point::(Point & pt)
복사생성자
{
    x = pt.x;
    y = pt.y;
}
 
int main()
{
    Point pt1;
    Point pt2(1516);
Point pt3 = pt2; 초기화
    pt1 = pt2; 대입
    Point pt4(pt2);
cs


*얕은 복사와 깊은 복사


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
class DynamicArray
{
public :
    char name[5];
    int * arr;
    DynamicArray(int arraySize);
    ~DynamicArray();
};
 
DynamicArray::DynamicArray(int arraySize)
{
    arr = new int[arraySize];
}
 
DynamicArray::~DynamicArray()
{
    cout << name << endl;
    delete[] arr;
    arr = NULL;
}
 
int main()
{
    int size;
    cout << "몇 개의 정수 : ";
    cin >> size;
 
    DynamicArray da1(size);
    DynamicArray da2 = da1;
    strcpy(da1.name,"da1");
    strcpy(da2.name,"da2");
 
    for (int i = 0; i < size; i++) {
        cin >> da1.arr[i];
    }
 
    for (int i = size - 1; i >= 0; i--) {
        cout << da1.arr[i]<<' ';
    }
    cout << endl;
}
cs

얕은 복사이기 때문에, da2가 da1의 arr(0x0112eb40)을 가리키고 있습니다. 

arr(0x0112eb40)이 da2에 의하여 delete 되고,

da1에 의하여 delete된 것이 한 번 더 delete 되어 오류가 발생합니다.


sol)깊은 복사

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
DynamicArray::DynamicArray(const DynamicArray & d)
깊은 복사
{
    this->size = d.size;
    this->arr = new int[this->size];
    for (int i = 0; i < this->size; i++) {
        this->arr[i] = d.arr[i];
    }
}
 
int main()
{
    int size;
    cout << "몇 개의 정수 : ";
    cin >> size;
 
    DynamicArray da1(size);
    strcpy(da1.name,"da1");
 
    for (int i = 0; i < size; i++) {
        cin >> da1.arr[i];
    }

    DynamicArray da2(da1);
    strcpy(da2.name, "da2");
 
    for (int i = size - 1; i >= 0; i--) {
        cout << da2.arr[i]<<' ';
    }
    cout << endl;
}
cs

da2의 arr이 da1의 arr과는 다른 메모리 공간을 가리키는 것을 볼 수 있습니다.


*class에서 const, 레퍼런스의 초기화

1
2
3
4
5
6
7
8
9
10
11
12
13
class Student
{
public :
    const int number;
    string & name;
    string Name;
    Student();
};
 
Student::Student() : number(10), name(Name)
{
    Name = "None\n";
}
cs

class의 멤버 변수 중, const reference 속성을 가진 멤버변수는 반드시 생성자에서 초기화 시켜주어야합니다.


*class에서 static의 초기화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Student
{
public :
    const int number;
    string & name;
    string Name;
    static int how_many;
    Student();
};
int Student::how_many = 0;
Student::Student() : number(10), name(Name)
{
    Name = "None\n";
    //how_many = 0; 에러
    how_many++;
}
cs

static의 경우, int Student::how_many = 0; 와 같은 형식으로 초기화시켜줍니다.


1
2
3
4
5
6
7
8
9
10
11
12
class Student
{
public :
    ...
    static void print();
};
 
void Student::print()
{
    cout << how_many;
    cout << number; 에러
}
cs

static 멤버 함수는 static 멤버 변수만을 사용할 수 있습니다.



*class의 const

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Student
{
 public:
    int n = 10;
    void print() { cout << n; }
    void c_print() const { cout << n; }
};
 
int main()
{
    const Student s;
    s.print(); 에러
    s.c_print();
}
cs

const의 속성을 갖는 class는 오로지 const 멤버 함수만 사용가능합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Point
{
private:
    int x = 10, y = 15;
public:
    int getX() const { return x; }
    int getY() { return y; }
};
 
int Area(const Point &p)
{
    return p.getX() * p.getY();
}
 
int main()
{
    const Point p;
    Area(p);
}
cs

객체 p는 const의 속성을 가지고 있어, const 멤버 함수만을 사용가능합니다.

이 때, getX()는 const 속성을 지니고 있지만, getY()는 지니고 있지 않아 오류가 발생합니다.


*inline 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Student
{
public :
    ...
    inline void func();
};
void Student::func()
{
    cout << "inline function" << endl;
}
int main()
{
    Student s;
    s.func();  => cout << "inline function" << endl;
}
cs

inline 함수를 호출하는 해당 위치로 함수의 내용이 들어갑니다.


*객체의 배열

1
2
3
4
5
6
7
8
9
10
11
12
13
class Student
{
 public:
    int n = 10;
    Student(int num) {
        n = num;
    }
};
 
int main()
{
    Student s[5= { Student(1), Student(2), Student(3), Student(4), Student(5) };
}
cs



*멤버 함수에 대한 포인터

1
2
3
4
5
6
7
8
9
10
11
typedef int (*FP1)();
typedef int (Point::*FP2)();
 
int main()
{
    Point p;
일반 함수에 대한 포인터
    FP1 pt = &Point::mul; 에러

멤버 함수에 대한 포인터
    FP2 ptr = &Point::mul;
}
cs


*class의 생성자와 소멸자

자식이 생성되기 위해선 부모가 먼저 생성되어야 합니다.

부모 class 생성 -> 자식 class 생성 -> 자식 class 소멸 -> 부모 class 소멸


*자식 class에 부모 class 생성자 지정하기

1
2
3
4
5
6
7
8
9
// HTMLWriter.h
class HTMLWriter : public DocWriter
{
public:
    HTMLWriter(void);
    HTMLWriter(const string& fileName, const string& content);
    ~HTMLWriter(void);
...
 
cs

1
2
3
4
5
6
7
8
9
10
11
// HTMLWriter.cpp
HTMLWriter::HTMLWriter(const string& fileName, const string& content)
: DocWriter( fileName, content)   부모의 생성자 지정
{
    // 디폴트 폰트를 지정한다.
    _fontName = "굴림";
    _fontSize = 3;
    _fontColor = "black";
}
...
 
cs

1
2
3
4
5
6
// Example.cpp
...
    HTMLWriter hw( "test.html""You must be a good programmer~!!");
    hw.Write();
...
 
cs


*Inheritance(상속) - 부모와 자식


대입

1
2
3
4
5
6
7
DocWriter dw;    // 부모 클래스의 객체 생성
HTMLWriter hw;    // 자식 클래스의 객체 생성
 
*부모 클래스의 객체를 자식 클래스의 객체로 대입
hw = dw; 에러        

*자식 클래스의 객체를 부모 클래스의 객체로 대입
dw = hw;
cs


포인터, 레퍼런스의 형변환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    DocWriter dw;        // 부모 클래스의 객체 생성
    HTMLWriter hw;
    HTMLWriter * phw = &dw; 에러 //다운캐스트
    HTMLWriter & rhw = dw; 에러
    
    DocWriter * pdw = &hw;//업캐스트
    DocWriter & rdw = hw;
 
 
    return 0;
}
cs


1
2
DocWriter * pdw = &hw; 업캐스트
HTMLWriter * phw2 = (HTMLWriter *)pdw; 업캐스트 후의 다운캐스트
cs

다운 캐스트 이후에 업 캐스트를 사용하면 에러가 발생하지 않습니다!!!


*다중상속

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class UnderGradStudent
{
    ...
    void Warn();    // 학사 경고
};
 
class DormStudent
{
    ...
    void Warn();    // 벌점 부여
};
 
// 중간 생략
 
UnderGrad_DormStudent ud;
ud.Warn();        // Error – 어떤 Warn() 을 말하는 지 알 수 없다.
ud.UnderGradStudent::Warn();  어떤 class의 함수 인지 명시
 
cs


*포함(Has-a)과 상속(Is-a)

포함 : 조립, 자동차는 바퀴, 핸들로 이루어진다. 사각형(Rect)은 점(Point)을 가지고 있다.

상속 : 모든 것을 갖는다. 사과는 과일의 한 종류이다. HTML 저장 class 는 Documnet 저장 class의 한 종류이다.

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