배움 저장소

[코테용C++ 핵심 정리] 챕터5. 구조 만들기 본문

Programming Language/C++

[코테용C++ 핵심 정리] 챕터5. 구조 만들기

시옷지읏 2023. 11. 18. 16:15

구조체


구조체와 배열의 차이

구조체는 여러 자료형을 묶어놓을 수 있다.

MyStruct a{
    int first;

    float second;
};

 

구조체의 패딩(padding)

MyStruct2 구조체 멤버변수의 총 크기는 5byte이지만 구조체 전체의 크기는 8byte이다.

컴파일러가 패딩을 추가하였다.

struct MyStruct
{
    int first; // 4 bytes
    int second; //4 bytes
};

struct MyStruct2
{
    int fist; // 4 bytes
    char second; // 1 bytes
};

int main()
{
    cout << sizeof(MyStruct) << endl;  // 8byte
    cout << sizeof(MyStruct2) << endl; // 8byte
    return 0;
}

 

클래스


인스턴스

- 클래스 자료형으로 생성된 변수를 통칭하여 인스턴스라 한다.

- 클래스에서 정의된 연산을 할 수 있다.- 클래스에서 정의된 데이터를 가지고 있다.

참고:

C++에서 int, float 같은 기본 자료형에서 인스턴스라는 용어를 사용하지 않는다.

Python은 기본 자료형도 class이기 때문에 인스턴스라는 용어를 사용할 수 있다.

 

this pointer

해당 인스턴스의 주소를 반환한다. 디버깅에 유용하게 사용된다.

생성자가 실행되기 전에 필요한 메모리 공간을 잡아놓기 때문에 this 포인터로 접근할 수 있다.

 

소멸자

동적할당받은 메모리를 delete로 반납할 때 호출된다.

Scope를 벗어날 때 호출된다.

프로그램이 종료되어 모든 메모리를 반납할 때 호출된다.

 

구글 스타일가이드

 

Google C++ Style Guide

Google C++ Style Guide Background C++ is one of the main development languages used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn ca

google.github.io

 

 

문자열 클래스 만들기


참고1. cout과 문자열

cout은 char* 혹은 char[]를 받으면 주소가 아닌 문자열을 출력한다.

null character가 나올때까지 출력한다.

 

참고2. *(ptr+i) vs ptr[i]

ptr[i]가 훨씬 간편하다.

*(ptr+i);
ptr[i];

 

참고3. 문자열 사이즈 vs null character

자체 문자열 클래스를 만든다면 문자열 사이즈와 null character 데이터를 동시에 가지고 있을 필요가 없다.

문자열 크기를 알고 있을 때 null character를 저장하지 말자.

 

- null character를 사용하지 않을 때 cout을 사용할 수 없다

- 새로 할당 받는 메모리의 크기가 더 클때 기존의 데이터만 옮기면 된다.

void Resize(int new_size)
{
	...
    for (int i = 0; i < (new_size < size_ ? new_size : size_); i++)
    {
        new_str[i] = str_[i];
    }
	...
}

 

헤더파일 사용법


클래스는 선언과 구현을 분리할 수 있다.

linking: 해당 클래스를 사용하면 컴파일러가 컴파일 된 구현부를 연결시킨다.

{
    "tasks": [
        {
            "args": [
                ....,
                "${fileDirname}/*.cpp", // cpp 파일을 모두 컴파일 하라
                ....,
            ],
        }
    ]
}

 

헤더가드

참고 : https://hoplite.tistory.com/83 #Header Guard 헤더가드 (전처리지시자)

 

 

파일 입출력


라이브러리

#include <fstream>

파일 출력

ofstream ofile; // output file stream

ofile.open("my_contacts.txt");
ofile << "안녕하세요? 반갑습니다.\n";
ofile << "두 번째 줄입니다.\n";
ofile << "세 번째 줄입니다.\n";
ofile.close();

 

파일 입력

char line[100];

ifstream ifile; // input file stream
ifile.open("my_contacts.txt");

int line_number = 0;
while (ifile.getline(line, sizeof(line)))
{
    cout << line_number << " : ";
    cout << line << endl;

    line_number += 1;
}

ifile.close();

 

getline 함수는 더 이상 값을 읽을 수 없을 때 false를 출력한다.

ifstream::getline();

 

전화번호부


assert

디버깅에 용이하다. 해당 Scope에서 해당 조건을 반드시 만족해야 할 때 사용한다.

 

Dereference VS Array index

Dereference와 Array index는 동일하다. 둘 다 값을 반환한다. 주소 값인줄 착각했음

int* arr = new int[5];

*(arr+4);
arr[4];
Comments