-
C++ 연습문제 8.5C++ 2021. 10. 30. 22:59728x90반응형
Array 클래스는 임의 개수의 int형 원소를 저장할 수 있는 클래스이다. 이르르 위해 배열을 가리키는 포인터 변수(int *ary_)와 원소의 개수를 의미하는 int형 변수(int cnt_)를 멤버 변수로 가지고 있다. 다음 main 함수와 실행 화면을 참고하여 Array 클래스를 작성해보라. 단, 객체 소멸 시 소멸자를 통해 해당 객체를 위해 동적으로 생성한 메모리를 해제해야만 한다.
main.cpp :
#include <iostream> #include "Array.h" using namespace std; int main() { Array ary1(5); Array ary2(7); Array ary3(ary1); ary2.Set(0, 11).Set(1, 12).Set(2, 13); ary1.Print(); ary2.Print(); ary3.Print(); return 0; }
내 코드(Array.h) :
#include <iostream> using namespace std; class Array { private: int* ary_; int cnt_; public: Array(const Array &ary) { cnt_ = ary.cnt_; ary_ = new int[cnt_]; for (int i = 0; i < cnt_; i++) ary_[i] = ary.ary_[i]; } Array(int cnt) { cnt_ = cnt; ary_ = new int[cnt_]; for (int i = 0; i < cnt_; i++) ary_[i] = i; } ~Array() { delete[] ary_; } Array &Set(int a, int b) { ary_[a] = b; return *this; } void Print() { for (int i = 0; i < cnt_; i++) { cout << ary_[i]; cout << " "; } cout << endl; } };
728x90반응형'C++' 카테고리의 다른 글
C++ 연습문제 9.8 (0) 2021.11.07 C++ 연습문제 9.2 (0) 2021.10.30 C++ 연습문제 7.9 (0) 2021.10.19 C++ 연습문제 7.4 (0) 2021.10.19 C++ 연습문제 6.4 (0) 2021.10.19