The Essentials of C++, David hunter

Chapter 3. Non-Primitive Data Types 비-원시 데이터 타입

3.1 Enumerated Types 열거형 데이터 타입

  • Enumerated types are defined as shown below.

  • 열거형(Enumerated types)은 아래와 같이 정의됩니다.

enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };
  • The values listed within the braces are called enumeration constants and are given integer values starting at zero. Variables of type enum may therefore appear anywhere integers may appear. However, integers cannt be directly assigned to enumerated types. Thus, the following is illegal:

  • 중괄호 안에 나열된 값들은 열거형 상수(enumeration constants)라고 하며, 0부터 시작하는 정수 값을 갖습니다. enum 유형의 변수는 따라서 정수가 사용될 수 있는 모든 곳에 나타날 수 있습니다. 그러나 정수는 열거형 유형에 직접 할당할 수 없습니다. 따라서 다음은 잘못된 예입니다:

Weekday d;
int i = 3;
d = i; // not allowed!
  • Should one wish to do this, a type cast must be performed, as illustrated below:

  • 만약 이를 원한다면, 아래와 같이 형 변환을 수행해야 합니다.

Weekday d;
int i = 3;
d = (Weekday) i; // allowed with type cast
  • The effect is to assign d the enumerated constant WEDNESDAY. Since most C++ implementations will not provide range checking unless specifically told to do so, programmers should be careful to avoid sequences such as:

  • 이 작업은 d에 열거형 상수 WEDNESDAY를 할당하는 효과가 있습니다. 대부분의 C++ 구현은 명시적으로 지시하지 않는 한 범위 검사를 제공하지 않을 것이므로, 프로그래머는 다음과 같은 시퀀스를 피하기 위해 주의해야 합니다:

int i = 10;
// ...
d = (Weekday) i; // executable but incorrect

내용 요약

  • 열거형은 일련의 상수 값을 정의하는 C++의 데이터 유형 중 하나입니다. 열거형은 주로 연관된 상수 값을 그룹화하고 가독성을 높이기 위해 사용됩니다.
  • 열거형은 다음과 같이 정의됩니다. 중괄호 안에 나열된 값들은 “열거 상수”라고 불리며, 0부터 시작하는 정수 값을 가집니다. 이러한 열거 상수는 열거형 유형으로 변수를 선언하면 사용할 수 있으며, 정수가 사용되는 곳이라면 어디에서나 사용할 수 있습니다.
  • 그러나 주의해야 할 점은 정수를 직접 열거형 유형에 할당할 수 없다는 것입니다. 즉, 정수 변수를 열거형 변수에 직접 할당하면 오류가 발생합니다. 이런 경우, 형 변환을 사용하여 정수를 열거형 값으로 변환해야 합니다.
  • 열거형 변수에 값을 할당하면 해당 열거 상수에 해당하는 값이 변수에 할당됩니다.
  • 마지막으로, 대부분의 C++ 구현에서는 범위 검사를 제공하지 않으므로, 정수 값을 열거형 변수에 할당할 때 조심해야 합니다. 만약 범위를 벗어나는 값이 할당되면 예상치 못한 결과가 발생할 수 있습니다. 그래서 형 변환을 사용하여 명시적으로 정수 값을 열거형으로 변환하는 것이 좋습니다.

3.2 Arrays 배열

  • An array definition and initialization are illustrated below.

  • 아래에 배열의 정의와 초기화 예제가 나와 있습니다.

int a[5] = {2, 3, 4, 5, 11};
  • This declares a to be an array of five integers and initializes it to contain the first five prime numbers. Array indices in C++ are numbered starting at zero and not at one. Thus, a[0] and a[4] are acceptable references, but a[5] does not exist. Again, range checking is usually not provided by default.

  • 다음은 a를 다섯 개의 정수 배열로 선언하고, 이 배열을 처음 다섯 개의 소수로 초기화합니다. C++에서 배열 인덱스는 0부터 시작하여 1이 아니라 0부터 번호가 매겨집니다. 따라서 a[0] 및 a[4]는 허용되는 참조입니다. 그러나 a[5]는 존재하지 않습니다. 다시 한 번, 기본적으로 범위 검사는 제공되지 않는 것이 일반적입니다.

  • The language does not support multidimensional arrays in the traditional sense. However, defining arrays of arrays has the same effect. Thus, one might define a matrix as:

  • 이 언어는 전통적인 의미에서 다차원 배열을 지원하지 않습니다. 그러나 배열의 배열을 정의하면 동일한 효과를 얻을 수 있습니다. 따라서 행렬을 다음과 같이 정의할 수 있습니다:

float matrix[100][100];
  • The notation matrix[1][10] refers to the element at row 1 column 10.

  • 표기법 matrix[1][10]은 1행 10열의 요소를 가리킵니다.

  • Arrays cannt be copied using the assignment operator. Thus, the following code sequence is illegal.

  • 배열은 할당 연산자를 사용하여 복사할 수 없습니다. 따라서 다음 코드 시퀀스는 잘못되었습니다.

int a[5], b[5];
...
a = b; // ILLEGAL!

3.3 Structures 구조체

  • Structures in C++ are the equivalent of what are called “records” in some other languages. They represent aggregations of related data items. Their declaration and initialization is illustrated below.

  • C++에서의 “구조체(Structures)”는 다른 언어에서 “레코드(records)”라고 불리는 것과 동등합니다. 이들은 관련된 데이터 항목들의 집합을 나타냅니다. 아래에 그 선언과 초기화 방법을 나타냈습니다.

struct student_record {
    int id;
    char classification;
    float gpa;
};

student_record r = {1012, 'J', 3.25};
  • The components of a record are referenced using the “.” operator. Thus, one could say r.id or r.gpa for example.

  • 레코드의 구성 요소는 “.” 연산자를 사용하여 참조됩니다. 예를 들어 r.id나 r.gpa와 같이 사용할 수 있습니다.

  • Structure variables may be used with the assignment operator. Thus, one may write:

  • 구조 변수는 할당 연산자와 함께 사용할 수 있습니다. 따라서 다음과 같이 작성할 수 있습니다:

student_record r = {1012, 'J', 3.25}, s;
...
s = r;

3.4 Unions 공용체

  • A union is a struct all of whose fields begin at the same memory address. A union occupies sufficient memory to store its largest field. Unions allow a single storage location to store values of different types, as illustrated below.

  • 공용체(union)는 모든 필드가 동일한 메모리 주소에서 시작하는 구조체(struct)입니다. 공용체는 가장 큰 필드를 저장하는 데 충분한 메모리를 차지합니다. 공용체는 다른 유형의 값을 저장하는 데 단일 저장 위치를 허용하며, 아래와 같이 설명합니다.

#include <iostream>

union union_example {
    int integer_value;
    float float_value;
};

int main()
{
    union_example u;
    u.integer_value = 12;
    std::cout << u.float_value;
    return 0;
}
  • Since u.integer_value and u.float_value occupy that same storage, the example stores the bit pattern for 12 in u then writes out whatever floating point number that bit pattern represents. A reference to u.integer_value interprets the value stored at u as an integer, while a reference to u.float_value interprets the value as a float.

  • u.integer_value와 u.float_value가 같은 저장 공간을 공유하기 때문에, 이 예제는 12의 비트 패턴을 u에 저장한 다음 해당 비트 패턴을 나타내는 부동 소수점 숫자를 출력합니다. u.integer_value를 참조하면 저장된 값을 정수로 해석하고, u.float_value를 참조하면 해당 값을 부동 소수점으로 해석합니다.

  • Unions are a potentially unsafe construct but can be convenient when used as fields within a structure, as in the example shown below. In this example, a union is used to declare an array of grades each of which can be either a letter grade or a numerical score.

  • 공용체(union)는 잠재적으로 안전하지 않은 구조체이지만, 아래 예제에서와 같이 구조체 내부 필드로 사용될 때 편리할 수 있습니다. 이 예제에서는 조합체를 사용하여 문자 등급 또는 숫자 점수 중 하나로 구성될 수 있는 성적 배열을 선언하는 데 사용됩니다.


#include <iostream>

union grade_value {
    float score;
    char letter;
};

enum grade_type { letter_grade, numerical_grade };

struct result_record {
    grade_type type;
    grade_value value;
};

int main() {
    result_record results[25];
    results[1].type = letter_grade;
    results[1].value.letter = 'A'; 
    // ...
    results[20].type = numerical_grade;
    results[20].value.score = 85.0f; 
    // ...
    return 0;
}

3.5 The typedef Statement

  • The typedef statement is used to create new type identifiers, as illustrated below.

  • typedef 문은 아래에 설명된대로 새로운 유형 식별자를 만들기 위해 사용됩니다.

typedef float Temperature;
typedef char String32[32];
typedef float Matrix[100][100];
  • The typedef statement consists of the key word typedef followed by an ordinary declaration statement. Subsequent to the sample statements, writing Temperature t is equivalent to writing float t, writing String 32 s is equivalent to writing char s[32] and writing Matrix m is equivalent to writing float m[100][100].

  • typedef 문은 typedef 키워드 뒤에 일반 선언문이 따르는 것으로 구성됩니다. 샘플 문장들 이후에 Temperature t를 작성하는 것은 float t를 작성하는 것과 동등하며, String32 s를 작성하는 것은 char s[32]를 작성하는 것과 동등하며, Matrix m를 작성하는 것은 float m[100][100]을 작성하는 것과 동등합니다.