The Essentials of C++, David hunter

Chapter 1. Language Fundamentals

1.1 Language Overview

  • C++ is and extension of the language C incorporating the features of object oriented programming. With the exception of those language features directly related to object oriented programming, the two languages are almost identical. This book assumes no prior knowledge of C, and in an effort to keep the text as tightly focused as possible no attempt has been made to clarify the points at which the two languages diverge. In order to familiarize the reader with the structure of the language, an annotated C++ program is presented in the table below.

  • C++는 객체 지향 프로그래밍 기능을 통합한 언어 C의 확장입니다. 객체 지향 프로그래밍과 직접 관련된 언어 기능을 제외하고는, 이 두 언어는 거의 동일합니다. 이 책은 C에 대한 사전 지식을 요구하지 않으며, 텍스트를 가능한 한 명확하게 유지하기 위해 두 언어가 다른 지점을 명확하게 설명하지 않으려고 노력했습니다. 언어의 구조에 익숙해지기 위해 주석이 달린 C++ 프로그램이 아래 표에 제시되어 있습니다.

  • The language provides two ways of specifying comments. Groups of lines may be marked as comments by bracketing them with the symbols “/*” and “*”. Alternately, the symbol “//” marks the beginning of a comment restricted to a single line. This is the preferred method.

  • 이 언어는 두 가지 방법으로 주석을 지정할 수 있습니다. 여러 줄의 그룹은 “/“와 “” 기호로 둘러싸여 주석으로 표시될 수 있습니다. 또한 “//” 기호는 한 줄에 제한된 주석의 시작을 나타냅니다. 이것이 선호되는 방법입니다.

  • A C++ program need not conform to a rigid outline. Variable declarations, type definitions, and function definitions may appear in any order provided that identifiers are declared before they are referenced. Typically, however, a C++ source file begins with a number of preprocessor directives (explained in subsequent chapters). Global type and variable definitions typically come next, followed by any number of function definitions. A C++ executable source file must contain an function called main. Execution, or the start of the program, begins with this function.

  • C++ 프로그램은 엄격한 구조를 준수할 필요가 없습니다. 변수 선언, 타입 정의 및 함수 정의는 참조되기 전에 식별자가 선언되는 한 어떤 순서로든 나타날 수 있습니다. 일반적으로는 C++ 소스 파일이 여러 전처리기 지시문으로 시작됩니다(이후 장에서 설명합니다). 전역 타입 및 변수 정의가 일반적으로 그 다음에 옵니다. 그리고 이어서 여러 개의 함수 정의가 올 수 있습니다. C++ 실행 가능한 소스 파일은 main 함수라는 함수를 포함해야 합니다. 실행 또는 프로그램의 시작은 이 함수에서 시작됩니다.

  • Identifiers in C++ may be of any length, must start with a letter, and can contain any combination of letters, digits, and the “_” charater. It uses the semicolon as a statement separator and braces “{}” to group statements.

  • C++에서 식별자는 어떤 길이든 가능하며, 반드시 문자로 시작해야 하며, 문자, 숫자 및 “_” 문자의 임의의 조합을 포함할 수 있습니다. C++은 문장 구분자로 세미콜론을 사용하고, 중괄호 “{}”를 사용하여 문장을 그룹화합니다.

  • C++ is case sensitive. Thus, the string “SUM”, “Sum”, and “sum” all represent distinct identifiers. The reserved words of the language must be given in lower case. A complete set of reserved words is presented in table 1.2.

  • C++는 대소문자를 구분합니다. 따라서 문자열 “SUM”, “Sum” 및 “sum”은 모두 서로 다른 식별자를 나타냅니다. 언어의 예약어는 모두 소문자로 제공되어야 합니다. 예약어의 완전한 목록은 표 1.2에 제시되어 있습니다.

    Table 1.1
    An Annotated C++ Program
// complier directives always begin with # 
// and are typically placed at the top of a file

// include the I/O functions
#include <iostream>

// define a constant
#define PI 3.1415927

// A function that, given a radius, returns the circumference
float circumf(float radius) {
    return 2 * PI * radius;
}

int main() { // The main function
    float r; // Declare r
    char c = 'y'; // Declare c and set to 'y'
    while (c == 'y') { // While c is equal to 'y', do ...
        // Output newline and prompt
        std::cout << "\nEnter the radius of the circle: ";
        std::cin >> r; // Input r
        std::cout << "Circumference: " << circumf(r) << '\n'; // Output circumference

        // Output prompt
        std::cout << "Enter y to continue, n to exit: ";
        std::cin >> c; // Input c
    } // End loop
    
    return 0;
}

1.2 Primitive Types 원시 자료형

  • The simple types provided by C++ are: int for integers, float or double for reals, and char for chracters. The distinction between float and double is machine dependent, but generally the double type occupies more storage and allows for greater accuracy of representation than does float.

  • C++에서 제공하는 기본 데이터 타입은 다음과 같습니다: 정수에 대한 int, 실수에 대한 float 또는 double, 문자에 대한 char입니다. float와 double 간의 구별은 기계마다 다르지만, 일반적으로 double 타입은 더 많은 저장 공간을 차지하며 float보다 더 정확한 표현이 가능합니다.

  • Other primitive types can be produced by prefacing the simple types with the keywords short, long, signed and unsigned. This produces types such as long unsiged int, signed char, and so forth. Signed types can store both positive and negative numbers while unsigned types store only non-negative values. Consequently, unsigned types can store a larger range of non-negative integers than can signed types. All integer and real types are by default signed, while character types are by default unsigned.

  • 다른 원시 자료형은 간단한 자료형 앞에 short, long, signed 및 unsigned 키워드를 붙여서 생성할 수 있습니다. 이로써 long unsigned int, signed char 등과 같은 자료형이 생성됩니다. signed 자료형은 양수와 음수 숫자를 모두 저장할 수 있지만, unsigned 자료형은 음수가 아닌 값만 저장합니다. 따라서 unsigned 자료형은 signed 자료형보다 더 큰 범위의 음수가 아닌 정수를 저장할 수 있습니다. 모든 정수와 실수 자료형은 기본적으로 signed이며, 문자 자료형은 기본적으로 unsigned입니다.

  • The meaning of the short and long modifiers is implementation dependent. Generally, however, long types occupy more storage than short types but can store a larger range of values.

  • short와 long 수정자의 의미는 구현에 따라 달라집니다. 일반적으로 long 타입은 short 타입보다 더 많은 저장 공간을 차지하지만 더 큰 범위의 값을 저장할 수 있습니다.

  • It is possible to omit the word “int” from a type description. Thus, the type indication long is equivalent to long int, and the indication unsigned is equivalent to unsigned int.

  • 타입 설명에서 “int” 단어를 생략하는 것이 가능합니다. 따라서 long이라는 타입 표시는 long int와 동등하며, unsigned라는 표시는 unsigned int와 동등합니다.

1.3 Constants 상수

  • Integer constants are expressed in the usual manner: 0, 1234, -98, etc. A constant beginning with “0x” is an integer expressed in hex notation: 0x0, 0xfab5, 0x056a, etc.

  • 정수 상수는 일반적인 방식으로 표현됩니다: 0, 1234, -98 등입니다. “0x”로 시작하는 상수는 16진법 표기법으로 표현된 정수입니다: 0x0, 0xfab5, 0x056a 등입니다.

  • Real number constants begin with a digit and contain a decimal point followed by digits. They are of type double by default. Float constants may be specified by affixing an “f”, as in “3.141592f”.

  • 실수 상수는 숫자로 시작하고 소수점 다음에 숫자가 따르는 형태로 표현됩니다. 이들은 기본적으로 double 타입입니다. float 상수는 “3.141592f”와 같이 “f”를 붙여서 지정할 수 있습니다.

  • Character constants are specified using single quotes. Non-printable charaters are expressed using backslash sequences. These are presented. Despite their appearance, these sequences are treated as single characters.

  • 문자 상수는 작은따옴표를 사용하여 지정됩니다. 출력되지 않는 문자는 백슬래시 시퀀스를 사용하여 표현됩니다. 이들은 다음과 같이 제시됩니다. 외형상의 모습과는 달리 이 시퀀스들은 하나의 문자로 처리됩니다.

  • The ‘\ooo’ sequence allows characters to be specified as a one-, two-, or three-digit octal number. There is no limit to the number of hex digits that may be specified using the ‘\x’ sequence. In either case, a sequence of hex or octal digits is considered to terminate at the first character that is not a legitimate digit of the specified base.

  • ‘\ooo’ 시퀀스를 사용하여 문자를 하나, 두 개 또는 세 개의 8진수 숫자로 지정할 수 있습니다. ‘\x’ 시퀀스를 사용하여 지정한 기수의 유효한 숫자가 아닌 첫 번째 문자에서 16진수 또는 8진수 숫자 시퀀스는 종료됩니다. ‘\x’ 시퀀스를 사용하여 지정할 수 있는 16진수 숫자의 개수에는 제한이 없습니다.

  • Character strings are specified using double quotes. Non-printable characters can be embedded in strings as shown in the examples below.

  • 문자열은 이중 따옴표를 사용하여 지정됩니다. 아래의 예시와 같이 문자열 내에 출력되지 않는 문자를 포함시킬 수 있습니다.


"Attention! \a\a Attention!"
"Hello World\n"
"\fPage #"
  • The use of character string in C++ programming is fully explored in a subsequent chapter.

  • C++ 프로그래밍에서 문자열 사용에 대한 자세한 내용은 이후 장에서 완전히 다루어집니다.

Table 1.2 C++ Reserved Words
       
asm auto break case
catch char class const
continue default delete do
double else enum extern
float for friend goto
if inline int long
new operator private protected
public register return short
signed sizeof static struct
switch template this throw
try typedef union unsigned
virtual void volatile while

1.4 Declarations 선언

  • Variable declaration in C++ consist of a type name followed by one or more variable names. Optionally, declarations may specify default values for variables. Below are some examples of C++ variable declarations:

  • C++에서 변수 선언은 타입 이름 다음에 하나 이상의 변수 이름이 오는 형태로 구성됩니다. 선택적으로 선언은 변수에 대한 기본값을 지정할 수도 있습니다. 아래는 C++ 변수 선언의 몇 가지 예시입니다.

long int i, j, k;
int sum = 0, count = 0;
char c = '\0';
  • Any declaration can be preceded by the key word const. This marks the identifier as being a read0only value. That is, its value may be accessed but not modified.

  • 어떤 선언이든 const 키워드로 선행될 수 있습니다. 이는 해당 식별자를 읽기 전용 값으로 표시합니다. 즉, 해당 값은 읽을 수는 있지만 수정할 수는 없습니다.

const float pi = 3.1415927;

1.5 Operators and Expressions 연산자와 표현식

  • The table on the next page presents the most commonly used C++ operators. Many of these are explained in subsequent chapters. The operators are grouped according to precedence, from highest precedence to lowest precedence. Unary and assignment operators are right associative, all others are left associative.

  • 다음 페이지의 표에서는 가장 흔히 사용되는 C++ 연산자들이 제시되어 있습니다. 이 중 많은 연산자들은 이후 장에서 설명됩니다. 연산자들은 우선순위에 따라 그룹화되며, 최고 우선순위부터 최하 우선순위까지 나열되어 있습니다. 단항 및 할당 연산자는 오른쪽에서 왼쪽으로 결합되며, 나머지 연산자들은 왼쪽에서 오른쪽으로 결합됩니다.

  • The logical operators result in a value of zero for false and one for true. Evaluation of logical expressions stops as soon as the result of the expression can be determined. For example, given the expression (expr1) && (expr2) && (expr3), if expr1 is false, then expr2 and expr3 are not evaluated. Since expr1 is false the entire expression will be false regardless of the values of expr2 and expr3. Similarly, if expr1 was true and expr2 was false, expr3 would not be evaluated. Expressions involving logical OR are evaluated until a true expression is encountered.

  • 논리 연산자는 거짓일 경우 0의 값을, 참일 경우 1의 값을 반환합니다. 논리식의 평가는 식의 결과가 결정되면 즉시 중단됩니다. 예를 들어, (expr1) && (expr2) && (expr3)와 같은 식이 주어졌을 때, expr1이 거짓이면 expr2와 expr3는 평가되지 않습니다. expr1이 거짓이므로 expr2와 expr3의 값에 관계없이 전체 식은 거짓이 됩니다. 마찬가지로, expr1이 참이고 expr2가 거짓이면 expr3는 평가되지 않습니다. 논리 OR을 포함하는 식은 참인 식이 나타날 때까지 평가됩니다.

  • The operators ++ and -- combine both assignment and arithmetic. The expression ++i is equivalent to the assignment statement i = i + 1, and --i is equivalent to i = i - 1. (This is not necessarily true if i and j are pointer variables, as discussed in chapter 4) Consequently, these operators can only be used with variables. That is, the statement ++(a+b) is illegal.

  • 연산자 ++ 및 --는 할당과 산술을 결합한 연산자입니다. 식 ++i는 할당 문 i = i + 1과 동등하며, --i는 i = i - 1과 동등합니다. (i와 j가 포인터 변수인 경우, 장 4에서 설명한 것과는 다를 수 있습니다.) 따라서 이러한 연산자는 변수와 함께만 사용할 수 있습니다. 즉, 문장 ++(a+b)는 잘못된 문법입니다.

  • Furthermore, these operators have different semantics depending upon whether they appear to the left or right of a variable. The distinction is illustrated below.

  • 뿐만 아니라, 이러한 연산자는 변수의 왼쪽이나 오른쪽에 나타나느냐에 따라 다른 의미를 가집니다. 이 차이점은 아래에서 설명됩니다.

i = 10;
j = ++i + 5; // j is 16 and i is 11
i = 10;
j = i++ + 5; // j is 15 and i is 11
  • In the first sequence, because the increment operator appears to the right of i it performs a pre-increment. In the second example it appears to the left and therefore performs a post-increment. That is, in the first example i is incremented before the addition; in the second it is incremented after the addition.

  • 첫 번째 시퀀스에서는 증가 연산자가 i의 오른쪽에 나타나므로 전위 증가를 수행합니다. 두 번째 예제에서는 왼쪽에 나타나므로 후위 증가를 수행합니다. 즉, 첫 번째 예제에서는 덧셈 전에 i가 증가되고, 두 번째 예제에서는 덧셈 후에 i가 증가됩니다.

Table 1.3 "Special" Character Constants
Expression Meaning
\0 null (ascii value 0)
\n newline
\t horizontal tab
\v vertical tab
\b backspace
\r carriage return
\f form feed
\? question mark
\a audible bell
\\ backslash
\” double quote
\’ single quote
\ooo octal character code
\xhhh hex character code
  • Assignment in C++ is treated no differently than other operators. It may therefore appear anywhere within an expression, as illustrated below.

  • C++에서 할당은 다른 연산자와 다르게 처리됩니다. 따라서 아래에 설명된 대로 식 내의 어느 곳에서나 나타날 수 있습니다.

float x, y;
int i = 10, j = 3;
y = (x = i) / j; // x is now 10, y is 3.333
float x, y;
int i = 10, j = 3;
y = x = i / j; // x and y are both 3
  • Also, because the operator is right associative, assignment statements with multiple targets such as x = y = z = 10.0 are acceptable.

  • 또한, 이 연산자는 오른쪽 연관성을 가지므로 x = y = z = 10.0과 같은 여러 대상을 가진 할당 문은 허용됩니다.

  • In addition to the “=” assignment operator, C++ also defines a set of operators that combine arithmetic and assignment. For example, the statement i *= j is equivalent to i = i * j. In general, the expression i op = j is equivalent to i = i op j where op is an arithmetic, logical, or bit-wise operator.

  • ”=” 할당 연산자 외에도, C++는 산술과 할당을 결합한 연산자 세트를 정의합니다. 예를 들어, 문장 i *= j는 i = i * j와 동등합니다. 일반적으로, i op = j 표현식은 op가 산술, 논리 또는 비트 연산자일 때 i = i op j와 동등합니다.

1.6 Type Conversion 타입 변환

  • C++ does a great deal of automatic type conversion in expressions and assignment statements. When expressions involve a mixture of long and short variables (or flat and double) C++ will convert all operands to the longer type and perform the specified operation. When expressions include both integers and reals, C++ converts the integers to reals and performs the operation. When the division operator is used on two integers the equotient is truncated and the result is an integer. This can cause some unintended results, as illustrated by the sequence below.

  • C++는 표현식과 할당문에서 자동으로 타입 변환을 수행합니다. 표현식이 long 및 short 변수 (또는 float 및 double)의 혼합물을 포함할 때, C++는 모든 피연산자를 더 긴 타입으로 변환하고 지정된 연산을 수행합니다. 정수와 실수가 모두 포함된 표현식의 경우, C++는 정수를 실수로 변환하고 연산을 수행합니다. 두 정수에 나눗셈 연산자를 사용할 때 몫이 잘릴 수 있으며 결과는 정수가 됩니다. 이로 인해 아래 시퀀스에서 설명하는 것처럼 의도치 않은 결과를 초래할 수 있습니다.

float x;
int i = 10, j = 3;
x = i / j;
  • Because i and j are both integers, integer division is performed and x is assigned the value 3, not 3.33333 as one might expect.

  • 정수인 i와 j 간의 나눗셈이 수행되어 x에는 3이 아닌 3.33333과 같이 예상할 수 있는 값이 아닌 3이 할당됩니다.

  • Character values may also be intemixed with reals and integers. In these cases, the integer value of the character is its ASCII value.

  • 문자 값은 실수와 정수와 혼합하여 사용될 수도 있습니다. 이러한 경우, 문자의 정수값은 해당 문자의 ASCII 값입니다.

  • Shorter values may be assigned to longer variables with no side effects. Long values may also be assigned to short variables, but doing so may result in a corrupted value since the high order bits of the long value are lost. Real values are truncated when assigned to integer variables. The effect of assigning double values to float variables is machine dependent. Usually, they will be rounded or truncated.

  • 보다 짧은 값을 더 긴 변수에 할당하는 것은 부작용이 없습니다. 더 긴 값은 짧은 변수에 할당될 수 있지만, 이렇게 하면 긴 값의 높은 자릿수 비트가 손실되어 손상된 값이 발생할 수 있습니다. 실수 값은 정수 변수에 할당될 때 절사(truncate)됩니다. 더블 값을 플로트 변수에 할당하는 경우 그 효과는 기계에 따라 다릅니다. 보통 반올림(round) 또는 절사(truncate)됩니다.

  • Type conversion can be made explicit throught the use of a type cast. A type cast has the form (type) expression and indicates that the expression is to be converted into the specified type. Type casting can be used to avert the problem identified earlier.

  • 타입 변환은 타입 캐스트(type cast)를 사용하여 명시적으로 수행할 수 있습니다. 타입 캐스트는 (type) expression 형식을 가지며, expression을 지정된 타입으로 변환해야 함을 나타냅니다. 타입 캐스팅은 이전에 식별된 문제를 피하기 위해 사용할 수 있습니다.

flat x;
int i = 10, j = 3;
x = (float) i / (float) j;
  • In this example, i and j are explicitly converted to float type and floating point division is therefore performed. Because implicit type conversion can have unintended side effects, it is recommended that programmers use explicit type casting whenever type conversion must occur.

  • 이 예제에서 i와 j는 명시적으로 float 타입으로 변환되고, 따라서 부동 소수점 나눗셈이 수행됩니다. 암묵적인 타입 변환은 의도하지 않은 부작용을 가질 수 있으므로, 타입 변환이 발생해야 할 때마다 프로그래머가 명시적인 타입 캐스팅을 사용하는 것이 권장됩니다.

1.7 Standard Input and Output 표준 입력 및 출력

  • Unfortunately, a complate understanding of C++ I/O cannot be reached until one has first grasped the concepts of objects and software libraries. Therefore a thorhough discussion of this topic is left for a later chapter. In order to use I/O in subsequent examples, however, the syntax is introduced here.

  • 유감스럽게도, C++ I/O의 완전한 이해는 객체와 소프트웨어 라이브러리의 개념을 먼저 이해한 후에 가능합니다. 따라서 이 주제에 대한 철저한 논의는 이후 장으로 남겨두었습니다. 그러나 이후의 예제에서 I/O를 사용하기 위해 여기서는 구문을 소개하겠습니다.

  • To read a series of values from standard input into a series of variables one uses a statement of the form:

  • 표준 입력에서 여러 값을 읽어들여 여러 변수에 저장하려면 다음과 같은 형식의 문장을 사용합니다:

cin >> var1 >> var2 >> var3 ...;
  • Variables are assigned values in order as they are encountered on the standard input device. Whitespace (blanks, tabs, and newlines) are skipped. The list of values read is called an input “stream”

  • 변수들은 표준 입력 장치에서 만날 때 순서대로 값을 할당받습니다. 공백(공백, 탭 및 개행)은 건너뜁니다. 읽어들인 값의 목록을 “입력 스트림”이라고 합니다.

  • Similarly, to write a series of values to standard output one uses a statement of the form:

cout << val1 << val2 << val3 ...;
  • 마찬가지로, 표준 출력에 일련의 값을 쓰려면 다음과 같은 형식의 문장을 사용합니다:

  • Note that new lines are not generated unless explicitly included in the output stream as shown below:

  • 새 줄은 아래와 같이 출력 스트림에 명시적으로 포함되지 않는 한 생성되지 않습니다:

cout << "The result is: " << result << '\n';
  • To provide access to these facilities a program must contain the statement #include , usually placed at the top of a source file.

  • 이러한 기능에 액세스하려면 프로그램에 일반적으로 소스 파일의 맨 위에 배치되는 다음과 같은 문장이 포함되어야 합니다:

#include <iostream>