Starting Out with C++: Early Objects 5th Edition Chapter 8 배열(Arrays) Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved
목 차 8.1 여러 값을 저장하는 배열 8.2 배열 원소에 접근 8.3 배열 값의 입출력 8.4 배열 초기화 8.1 여러 값을 저장하는 배열 8.2 배열 원소에 접근 8.3 배열 값의 입출력 8.4 배열 초기화 8.5 배열 값의 처리 8.6 병렬 배열 사용하기 8.7 typedef 문 © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 2
목 차(계속) 8.8 함수 인자로서의 배열 8.9 2차원 배열 8.10 3 차원 이상의 배열 8.11 벡터 8.8 함수 인자로서의 배열 8.9 2차원 배열 8.10 3 차원 이상의 배열 8.11 벡터 8.13 구조체 배열 8.14 클래스 객체 배열 © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 3
8.1 여러 값을 저장하는 배열 배열(Array): 여러 개의 동일한 자료값을 저장할 수 있는 변수. 값은 인접한 메모리 상에 연속적으로 저장된다. 연산자[] 를 사용하여 선언한다. const int ISIZE = 5; int tests[ISIZE]; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 4
Array Storage in Memory 배열 정의 int tests[ISIZE]; // SIZE is 5 다음 메모리를 할당 first element second element third element fourth element fifth element © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 5
배열 용어 다음 정의에서 int tests[ISIZE]; int : 배열 요소의 자료형 tests : 배열의 이름 ISIZE, in [ISIZE], is the size declarator. 배열 요소의 수. 배열의 크기 : 할당된 바이트 수 (number of elements) * (bytes needed for each element) © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 6
배열 용어 예 예: 가정 int 는 4 bytes, double은 8 bytes const int ISIZE = 5, DSIZE = 10; int tests[ISIZE]; // holds 5 ints, array // occupies 20 bytes double volumes[DSIZE];// holds 10 doubles // array is 80 bytes © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 7
8.2 배열 원소에 접근 Each array element has a subscript(첨자), used to access the element. Subscripts start at 0 subscripts 0 1 2 3 4 © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 8
Accessing Array Elements Array elements (accessed by array name and subscript) can be used as regular variables tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; cout << tests; // illegal due to // missing subscript 0 1 2 3 4 tests © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 9
배열 첨자 배열 첨자 : 정수 상수, 정수 변수, 정수 수식 예: Subscript is cin >> tests[3]; int constant cout << tests[i]; int variable cout << tests[i+j]; int expression © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 10
8.3 배열 값의 입출력 To access a single element of an array, use a subscript (as previously shown) const int ISIZE = 5; int tests[ISIZE]; // Define 5-elt. array cout << "Enter first test score "; cin >> tests[0]; Related, sample programs from the text are noted. See pr8-01.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 11
모든 배열 요소의 입, 출력 To access each element of an array Use a loop Let the loop control variable be the array subscript A different array element will be referenced each time through the loop for (i = 0; i < 5; i++) cout << tests[i] << endl; See pr8-02.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 12
파일로부터 배열 자료 입력 const int ISIZE = 5, sales[ISIZE]; ifstream dataFile; datafile.open("sales.dat"); if (!dataFile) cout << "Error opening data file\n"; else { // Input daily sales for (int day = 0; day < ISIZE; day++) dataFile >> sales[day]; dataFile.close(); } See pr8-03.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 13
첨자 범위 검사 There are no checks in C++ that an array subscript is in range An invalid array subscript can cause program to overwrite other memory Example: const int ISIZE = 3; int i = 4; int num[ISIZE]; num[i] = 25; See pr8-04.cpp num [0] [1] [2] 25 © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 14
8.4 배열 초기화 배정문을 이용한 초기화 초기화 목록을 이용한 초기화 tests[0] = 79; tests[1] = 82; // etc. 초기화 목록을 이용한 초기화 const int ISIZE = 5; int tests[ISIZE] = {79,82,91,77,84}; See pr8-05.cpp, pr8-06.cpp, and pr8-07.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 15
배열의 부분적 초기화 If array is initialized at definition with fewer values than the size declarator of the array, remaining elements will be set to 0 or NULL int tests[ISIZE] = {79, 82}; Initial values used in order; cannot skip over elements to initialize noncontiguous range 79 82 See pr8-08.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 16
묵시적인 배열 크기 초기화 목록의 크기에 따라 배열 크기 결정 short quizzes[]={12,17,15,11}; Must use either array size declarator or initialization list when array is defined 12 17 15 11 © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 17
8.5 배열 값의 처리 배열 개별 요소는Array elements can be 다른 변수처럼 동일하게 다루어진다. 산술 수식, 관계 수식 등에서 사용된다. 예: if (principalAmt[3] >= 10000) interest = principalAmt[3] * intRate1; else interest = principalAmt[3] * intRate2; See pr8-09.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 18
배열 요소와 함께 증가, 감소 연산자의 사용 When using ++ and -- operators, don’t confuse the element with the subscript tests[i]++; // adds 1 to tests[i] tests[i++]; // increments i, but has // no effect on tests © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 19
배열 요소의 합 단순 루프의 사용 : 합계 구하기 합계를 구한 후, 평균 구하기 float average, sum = 0; for (int tnum=0; tnum< ISIZE; tnum++) sum += tests[tnum]; 합계를 구한 후, 평균 구하기 average = sum/5; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 20
배열의 최대값 구하기 Use a loop to examine each element and find the largest element (i.e., one with the largest value) int largest = tests[0]; for (int tnum = 1; tnum < ISIZE; tnum++) { if (tests[tnum] > largest) largest = tests[tnum]; } cout << "Highest score is " << largest; A similar algorithm exists to find the smallest element See pr8-10.cpp and pr8-11.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 21
string 객체 Can be processed using array name Entire string at once or One element at a time (by using a subscript) string city; // #include <string> cout << "Enter city name: "; cin >> city; See pr8-12.cpp 'S' 'a' 'l' 'e' 'm' city[0] city[1] city[2] city[3] city[4] © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 22
8.6 병렬 배열 사용하기 병렬 배열(Parallel arrays): 관련된 자료를 가지는 둘 이상의 배열 첨자(Subscript) 사용 같은 첨자의 원소는 연관된다. 같은 자료형을 저장하여야 할 필요는 없다. © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 23
병렬 배열 예 const int ISIZE = 5; string name[ISIZE]; // student name float average[ISIZE]; // course average char grade[ISIZE]; // course grade 1 2 3 4 name average grade © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 24
병렬 배열 사용하기 예 const int ISIZE = 5; string name[ISIZE]; // student name float average[ISIZE]; // course average char grade[ISIZE]; // course grade ... for (int i = 0; i < ISIZE; i++) cout << " Student: " << name[i] << " Average: " << average[i] << " Grade: " << grade[i] << endl; See pr8-13.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 25
8.7 typedef 문 단순 또는 구조체 자료형에 대한 별칭을 생성한다. 형식: 예: typedef existingType newName; 예: typedef unsigned int Uint; Uint tests[ISIZE]; // array of // unsigned ints © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 26
Typedef의 사용 프로그램 코드를 읽기 쉽게 한다. 특정 형의 배열에 대한 별칭을 생성하는데 사용 될 수 있다. // Define yearArray as a data type // that is an array of 12 ints typedef int yearArray[MONTHS]; // Create two of these arrays yearArray highTemps, lowTemps; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 27
8.8 함수 인자로서의 배열 배열 매개변수를 가지는 함수를 정의하기 위해, []을 사용 함수호출 시 인자로 배열 이름만 사용 // Function prototype void showScores(int []); // Function header void showScores(int tests[]) // Function call showScores(tests); © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 28
배열 요소 전달 Passing a single array element to a function is no different than passing a regular variable of that data type Function does not need to know the value it receives is coming from an array displayValue(score[i]); // call void displayValue(int item) // header { cout << item << endl; } See pr8-14.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 29
배열 전체를 전달 showScores(tests, 5); // call Just use array name, without any brackets, as the argument Can also pass array size so the function knows how many elements to process showScores(tests, 5); // call void showScores(int[], int); // prototype void showScores(int A[], int size) // header See pr8-15.cpp and pr8-18.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 30
Using typedef with a Passed Array Can use typedef to simplify function prototype and heading // Make intArray an integer array // of unspecified size typedef int intArray[]; // Function prototype void showScores(intArray, int); // Function header void showScores(intArray tests, int size) See pr8-16.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 31
함수에서 배열 수정하기 Array parameters in functions are similar to reference variables Changes made to array in a function are made to the actual array in the calling function Must be careful that an array is not inadvertently changed by a function See pr8-17.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 32
8.9 2차원 배열 Can define one array for multiple sets of data 8.9 2차원 배열 Can define one array for multiple sets of data Like a table in a spreadsheet Use two size declarators in definition int exams[4][3]; Number of rows Number of cols © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 33
Two-Dimensional Array Representation int exams[4][3]; Use two subscripts to access element exams[2][2] = 86; columns exams[0][0] exams[0][1] exams[0][2] exams[1][0] exams[1][1] exams[1][2] exams[2][0] exams[2][1] exams[2][2] exams[3][0] exams[3][1] exams[3][2] r o w s See pr8-19.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 34
정의 시에 초기화 Two-dimensional arrays are initialized row-by-row int exams[2][2] = { {84, 78}, {92, 97} }; Can omit inner { } 84 78 92 97 © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 35
Passing a Two-Dimensional Array to a Function Use array name as argument in function call getExams(exams, 2); Use empty [] for row and a size declarator for col in the prototype and header // Prototype, where NUM_COLS is 2 void getExams(int[][NUM_COLS], int); // Header void getExams (int exams[][NUM_COLS], int rows) See pr8-20.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 36
Using typedef with a Two-Dimensional Array Can use typedef for simpler notation typedef int intExams[][2]; ... // Function prototype void getExams(intExams, int); // Function header void getExams(intExams exams, int rows) © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 37
8.10 3 차원 이상의 배열 Can define arrays with any number of dimensions 8.10 3 차원 이상의 배열 Can define arrays with any number of dimensions short rectSolid(2,3,5); double timeGrid(3,4,3,4); When used as parameter, specify size of all but 1st dimension void getRectSolid(short [][3][5]); See pr8-21.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 38
8.11 벡터 표준 템플릿(Standard Template Library :STL)에서 정의. (컨테이너:container) 16장에서 설명 벡터 vector 헤드 파일을 include #include <vector> 배열과 같이 원소 집합을 저장 융통성을 가지는 원소 개수 - can grow and shrink 정의 시 크기를 규정할 필요가 없다. 더 큰 크기가 요구되면 공간을 자동적으로 부가한다. © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 39
벡터 어떠한 형의 값도 저장할 수 있다. 벡터 요소에 접근하기 위해 []를 사용한다. 벡터를 정의할 때, 자료형을 규정한다. vector<int> scores; vector<double> volumes; 벡터 요소에 접근하기 위해 []를 사용한다. © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 40
벡터 정의하기 정수형 벡터 정의(starts with 0 elements) 초기 크기가 30인 int 벡터 정의 vector<int> scores; 초기 크기가 30인 int 벡터 정의 vector<int> scores(30); 크기가 20인 int 벡터를 정의하고, 모든 요소에 초기값으로 0 배정하기 vector<int> scores(20, 0); scores를 int 벡터로 정의하고 finals의 모든 원소들의 값을 scores에 복사한다. vector<int> scores(finals); ( ) 사용 See pr8-22.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 41
프로그램 8-22 (P. 510) 벡터에 값 저장, 검색 © 2006 Pearson Education. // This program stores employee hours worked and hourly pay rates // in two vectors. #include <iostream> #include <iomanip> #include <vector> // Needed to use vectors using namespace std; int main() { const int NUM_EMPS = 5; vector <int> hours(NUM_EMPS); // Define a vector of integers vector <double> payRate(NUM_EMPS); // Define a vector of doubles double grossPay; int index; // Loop counter // Get employee work data cout << "Enter the hours worked and hourly pay rates of " << NUM_EMPS << " employees. \n"; for (index = 0; index < NUM_EMPS; index++) cout << "Hours worked by employee #" << (index + 1) << ": "; cin >> hours[index]; cout << "Hourly pay rate for employee #" << (index + 1) << ": "; cin >> payRate[index]; } // Display the data cout << "\nHere is the gross pay for each employee:\n"; cout << fixed << showpoint << setprecision(2); grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << setw(7) << grossPay << endl; return 0; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 42
벡터 크기 변경 시작 크기가 정해지진 않은 벡터나 이미 가득 차 있는 벡터에 값을 저장할 때 멤버 함수 push_back 사용 // Add a new element holding a 75 scores.push_back(75); // 벡터의 끝에 인자 값을 추가 프로그램 8-23 참조(p.512) size 멤버 함수 : 벡터의 현재 크기를 보여준다. howbig = scores.size(); 프로그램 8-24 참조(p.514) See pr8-23.cpp and pr8-24.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 43
프로그램 8-23 (P. 512) push_back 멤버 함수 사용 // This program stores employee hours worked and hourly pay rates // in two vectors. It demonstrates the use of the push_back member // function to add new elements to the vectors. #include <iostream> #include <iomanip> #include <vector> // Needed to use vectors using namespace std; int main() { vector<int> hours; // hours is an empty integer vector vector<double> payRate; // payRate is an empty double vector double grossPay; int numEmployees; // The number of employees int index; // Loop counter // Get the number of employees cout << "How many employees do you have? "; cin >> numEmployees; // Input the payroll data cout << "Enter the hours worked and hourly pay rates of the " << numEmployees << " employees. \n"; for (index = 0; index < numEmployees; index++) int tempHours; // Holds the number of hours entered double tempRate; // Holds the pay rate entered cout << "Hours worked by employee #" << (index + 1) << ": "; cin >> tempHours; hours.push_back(tempHours); // Add an element to hours cout << "Hourly pay rate for employee #" << (index + 1) << ": "; cin >> tempRate; payRate.push_back(tempRate); // Add an element to payRate } // Display each employee's gross pay cout << "\nHere is the gross pay for each employee:\n"; cout << fixed << showpoint << setprecision(2); grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << setw(7) << grossPay << endl; return 0; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 44
프로그램 8-24 (P. 514) size 멤버 함수 사용 © 2006 Pearson Education. // This program demonstrates the vector size member function. #include <iostream> #include <vector> using namespace std; // Function prototype void showValues(vector<int>); int main() { vector<int> values; for (int count = 0; count < 7; count++) values.push_back(count * 2); showValues(values); return 0; } //**************************************************************** // Definition of function showValues * // This function accepts an int vector as its sole argument. * // It displays the value stored in each of the vector's elements.* void showValues(vector<int> vect) for (int count = 0; count < vect.size(); count++) cout << vect[count] << " "; cout << endl; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 45
벡터로부터 원소 제거하기 pop_back 멤버 함수 : 벡터로부터 마지막 원소를 제거한다. // void 반환 scores.pop_back(); clear 멤버 함수 : 벡터의 모든 원소를 제거한다. scores.clear(); empty 멤버 함수 : 비어 있는 벡터 확인하기 while (!scores.empty()) ... See pr8-25.cpp, pr8-26.cpp, and pr8-27.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 46
프로그램 8-25 (P. 514) pop_back 멤버 함수 사용 // This program demonstrates the vector size, push_back, // and pop_back member functions. #include <iostream> #include <vector> using namespace std; int main() { vector<int> values; // Store values in the vector values.push_back(1); values.push_back(2); values.push_back(3); cout << "The size of values is " << values.size() << endl; // Remove a value from the vector cout << "Popping a value from the vector...\n"; values.pop_back(); cout << "The size of values is now " << values.size() << endl; // Now remove another value from the vector // Remove the last value from the vector return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 47
프로그램 8-26 (P. 516) clear 멤버 함수 사용 // This program demonstrates the vector clear member function. #include <iostream> #include <vector> using namespace std; int main() { vector<int> values(100); cout << "The values vector has " << values.size() << " elements.\n"; // 100 cout << "I will call the clear member function...\n"; values.clear(); cout << "Now the values vector has " << values.size() << " elements.\n"; // 0 return 0; } © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 48
프로그램 8-27 (P. 516) empty 멤버 함수 사용 © 2006 Pearson Education. // This program demonstrates the vector empty member function. #include <iostream> #include <vector> using namespace std; // Function prototype double avgVector(vector<int>); int main() { vector<int> values; int numValues; double average; cout << "How many values do you wish to average? "; cin >> numValues; for (int count = 0; count < numValues; count++) { int tempValue; cout << "Enter an integer value: "; cin >> tempValue; values.push_back(tempValue); } average = avgVector(values); cout << "Average: " << average << endl; return 0; double avgVector(vector<int> vect) int total = 0; // accumulator double avg = 0.0; if (vect.empty()) // Determine if the vector is empty. cout << "No values to average.\n"; else { for (int count = 0; count < vect.size(); count++) total += vect[count]; avg = static_cast<double>(total) / vect.size(); return avg; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 49
8.13 구조체 배열 구조체도 배열의 원소로 사용될 수 있다. { int studentID; string name; struct Student { int studentID; string name; short year; double gpa; }; const int CSIZE = 30; Student class[CSIZE]; // Holds 30 // Student structures © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 50
구조체 배열 배열 첨자를 사용하여 배열의 특정 구조체에 접근한다. 해당 구조체의 멤버에 접근하기 위해 도트 연산자를 사용한다. cin >> class[25].studentID; cout << class[i].name << " has GPA " << class[i].gpa << endl; // class[2].name[3] = ’t’; See pr8-29.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 51
프로그램 8-29 (P. 522) 구조체 배열 사용 workers[0] hours payRate … … hours // This program uses an array of structures to hold employee payroll data. #include <iostream> #include <iomanip> using namespace std; struct PayInfo { int hours; // Hours worked double payRate; // Hourly pay rate }; int main() const int NUM_EMPS = 5; int index; PayInfo workers[NUM_EMPS]; // Define an array of structures double grossPay; cout << "Enter the hours worked and hourly pay rates of " << NUM_EMPS << " employees. \n"; for (index = 0; index < NUM_EMPS; index++) cout << "Hours worked by employee #" << (index + 1); cout << ": "; cin >> workers[index].hours; cout << "Hourly pay rate for employee #"; cout << (index + 1) << ": "; cin >> workers[index].payRate; } // Display each empolyee's gross pay cout << "\nHere is the gross pay for each employee:\n"; cout << fixed << showpoint << setprecision(2); grossPay = workers[index].hours * workers[index].payRate; cout << "Employee #" << (index + 1); cout << ": $" << setw(7) << grossPay << endl; return 0; workers[0] hours payRate … … hours workers[4] payRate © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 52
구조체 배열의 초기화 PayInfo workers[5] = { PayInfo(10, 9.75), Struct PayInfo { int hours; double patRate; PayInfo(int h=0, double p=0.0) // 생성자 함수 { hours = h; payRate = p; } }; PayInfo workers[5] = { PayInfo(10, 9.75), PayInfo(15, 8.62), PayInfo(20, 10.50), PayInfo(40, 18.75), PayInfo(40, 15.65) }; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 53
8.14 클래스 객체 배열 클래스 객체도 배열의 요소로 사용될 수 있다. class Square { private: int side; public: Square(int s = 1) { side = s; } int getSide() { return side; } }; Square shapes[10]; // Create array of 10 // Square objects © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 54
클래스 객체 배열 배열 첨자를 사용하여 배열의 특정 객체를 접근한다. 해당 객체의 멤버에 접근하기 위해 도트 연산자를 사용한다. for (i = 0; i < 10; i++) cout << shapes[i].getSide() << endl; See pr8-30.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 55
객체 배열의 초기화 모든 객체에 대해 같은 초기화를 수행할 때 디폴트 생성자를 사용한다. 각 객체에 대해 특정 초기값을 제공하기 위해 초기화 목록을 사용한다. Square shapes[5] = {1,2,3,4,5}; 초기화 목록 수가 작은 경우에는 나머지 객체에 대해서는 디폴트 생성자가 사용된다. Square boxes[5] = {1,2,3}; See pr8-31.cpp and pr8-32.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 56
프로그램 8-31 (P. 527) 객체 배열 사용 시 디폴트 생성자 사용 © 2006 Pearson Education. // This program demonstrates how the default constructor // initializes values for each object in an array of objects. #include <iostream> #include <iomanip> #include <cmath> using namespace std; // Circle class declaration class Circle { private: double radius; public: Circle() { radius = 1.0;} // Default constructor Circle(double r) {radius = r;} // Overloaded constructor void setRadius(double r) {radius = r;} double findArea() {return 3.14 * pow(radius, 2);} }; const int NUM_CIRCLES = 4; int main() { int index; Circle sphere[NUM_CIRCLES]; // Define array of Circle objects // Each Circle object has the radius // value set by the default constructor. // Display area of each object cout << fixed << showpoint << setprecision(2); cout << "\nHere are the areas of the " << NUM_CIRCLES << " spheres.\n"; for (index = 0; index < NUM_CIRCLES; index++) { cout << "sphere " << (index+1) << setw(8) << sphere[index].findArea() << endl; } return 0; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 57
프로그램 8-32 (P. 528) 초기화 목록과 디폴트 생성자 사용 // This program demonstrates how an overloaded constructor // that accepts an argument can be invoked for multiple objects // when an array of objects is created. #include <iostream> #include <iomanip> #include <cmath> using namespace std; // Circle class declaration class Circle { private: double radius; public: Circle() { radius = 1.0;} // Default constructor Circle(double r) {radius = r;} // Overloaded constructor void setRadius(double r) {radius = r;} double findArea() {return 3.14 * pow(radius, 2);} }; const int NUM_CIRCLES = 4; int main() { int index; // Define an array that holds 4 Circle objects. Use an initialization // list to call the constructor using one double argument for the first 3 objects. The default constructor will be called for the final object. Circle sphere[NUM_CIRCLES] = {0.0, 2.0, 2.5}; // Display area of each object cout << fixed << showpoint << setprecision(2); cout << "\nHere are the areas of the " << NUM_CIRCLES << " spheres.\n"; for (index = 0; index < NUM_CIRCLES; index++) { cout << "sphere " << (index+1) << setw(8) << sphere[index].findArea() << endl; } return 0; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 58
객체 배열의 초기화 2 이상의 인자를 취하는 생성자로 객체가 초기화되면, 초기화 목록은 객체에 대한 생성자 호출을 포함하여야 한다. Rectangle spaces[3] = { Rectangle(2,5), Rectangle(1,3), Rectangle(7,7) }; See pr8-33.cpp © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 59
프로그램 8-33 (P. 530) 2 이상의 인자를 취하는 생성자 호출로 초기화 목록 구성하기 // This program demonstrates how an overloaded constructor that accepts more // than one argument can be invoked when an array of objects is created. #include <iostream> #include <cmath> using namespace std; // Circle class declaration class Circle { private: double radius; int centerX, centerY; public: // Default constructor Circle() { radius = 1.0; centerX = centerY = 0;} // Overloaded constructor that accepts one argument Circle(double r) {radius = r; centerX = centerY = 0;} // Overloaded constructor that accepts three arguments Circle(double r, int x, int y) {radius = r; centerX = x; centerY = y;} double findArea() {return 3.14 * pow(radius, 2);} int getX() {return centerX;} int getY() {return centerY;} }; © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 60
Circle(r,x,y) Circle(r) Circle() int main() { const int NUM_CIRCLES = 4; int index; // Define an array that holds 4 Circle objects. // Invoke the constructor using 3 arguments for object 0. // Invoke the constructor using 1 argument for object 1. // Invoke the constructor using 3 arguments for object 2. // Invoke the default constructor for object 4. Circle sphere[NUM_CIRCLES] = { Circle(0.0, 2, 4), 2.0, Circle(2.5, -1, -1) }; // Display center coordinates and area of each Circle object for (index = 0; index < NUM_CIRCLES; index++) { cout << "sphere " << (index+1) << " with center at (" << sphere[index].getX() << "," << sphere[index].getY() << ") has an area of " << sphere[index].findArea() << endl; } return 0; Circle(r) Circle() © 2006 Pearson Education. All Rights Reserved Chapter 8 Starting Out with C++: Early Objects 5/e slide 61
Starting Out with C++: Early Objects 5th Edition Chapter 8 Arrays(배열) Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved