C++

C++ 연습문제 9.11

wooob 2021. 11. 7. 16:44
728x90

임의 길이의 int형 배열을 다룰 수 있는 Array 클래스를 작성해보라. 멤버 변수로는 배열의 크기(int count_), 배열 포인터(int* ary_)를 가지고 있다. 객체 생성 시 각 원소의 값은 rand 함수를 사용하여 임의의 값(0 ~ 9)으로 채우도록 하라. 소멸자에서는 동적으로 생성한 메모리를 해제해야 한다. 다음 main 함수와 같이 실행될 수 있도록 만들어보라.

 

main.cpp : 

#include <iostream>
#include <ctime>
#include "array.h"
using namespace std;

int main() {
	srand((unsigned)time(NULL));

	Array ary1(3);
	Array ary2(5);
	
	cout << ary1 << endl;
	cout << ary2 << endl;

	ary1 = ary2;

	cout << ary1 << endl;
	cout << ary2 << endl;

	return 0;
}

 

내 코드 (array.h) :

#include <iostream>
#include <cstdlib>
using namespace std;

class Array {
private:
	int cnt_;
	int* ary_;

public:
	Array& operator=(const Array& ary) {
		delete[] ary_;
		cnt_ = ary.cnt_;
		ary_ = new int[cnt_];

		for (int i = 0; i < cnt_; i++)
			ary_[i] = ary.ary_[i];

		return (*this);
	}

	friend ostream& operator<<(ostream& out, const Array& ary);

	Array(int cnt) {
		cnt_ = cnt;
		ary_ = new int[cnt];

		for (int i = 0; i < cnt_; i++)
			ary_[i] = rand() % 10;
	}

	~Array() {
		delete[] ary_;
	}
};

ostream& operator<<(ostream& out, const Array& ary) {
	for (int i = 0; i < ary.cnt_; i++)
		out << ary.ary_[i] << "     ";
	return out;
}
728x90