끄적끄적 개발공부

#Class 동적할당 이어 붙이기 (1)

HYuk 2021. 4. 30. 03:23
728x90

Class 에서 함수를 생성하고,

동적할당을 통해 입력받을 개수, 그리고 입력값을 받고

출력할 수 있는 Class 문을 만들어 보려고 한다.

 

이때, 처음 동적할당을 하고 두번째 동적할당을 할 때

이전의 동적할당 하면서 입력했던값 + 새로운 동적할당의 값 

둘다 한번에 출력할 수 있도록 하려고 한다.

 

Linked List를 사용하는 거 같은데

아직은 잘 모르겠다.


현재 내가 사용한 방법은

처음 동적할당 예를들어 [5]개 를 받고

두번째 동적할당시 [2]개를 받으면

 

이때 [7]개의 동적할당을 새로이 하고

[0]~[4]까지는 이전 동적할당내용을 복사해주고 

[5]~ [6]까지는 새로 입력받은값을 넣어줬다.

 

해당코드는 다음과 같다

 

#include "stdafx.h"
#include <iostream>

using namespace std;

class CStudent
{
	char szName[16];
	int iKor;
	int iEng;
	int iMath;
	int iTotal;
	float fAver;

public:
	CStudent* Set_Studentinfo(CStudent* _pStudent, int& _iCount)
	{
		int iTemp = 0;

		cout << "학생 수: ";
		cin >> iTemp;
		_iCount += iTemp;
		CStudent* pStudent = new CStudent[_iCount];

		for (int i = 0; i < _iCount-iTemp ; ++i)
		{
			strcpy_s(pStudent[i].szName,16, _pStudent[i].szName);
			pStudent[i].iKor = _pStudent[i].iKor;
			pStudent[i].iEng = _pStudent[i].iEng;
			pStudent[i].iMath = _pStudent[i].iMath;
			pStudent[i].iTotal = _pStudent[i].iTotal;
			pStudent[i].fAver = _pStudent[i].fAver;
		}

		delete[] _pStudent;
		_pStudent = nullptr;

		for (int i = 0; i < iTemp; ++i)
		{
			cout << "이름: ";
			cin >> pStudent[_iCount-iTemp+i].szName;
			cout << "국어 점수: ";
			cin >> pStudent[_iCount - iTemp + i].iKor;
			cout << "영어 점수: ";
			cin >> pStudent[_iCount - iTemp + i].iEng;
			cout << "수학 점수: ";
			cin >> pStudent[_iCount - iTemp + i].iMath;
			pStudent[_iCount - iTemp + i].iTotal = pStudent[_iCount - iTemp + i].iKor + pStudent[_iCount - iTemp + i].iEng + pStudent[_iCount - iTemp + i].iMath;
			pStudent[_iCount - iTemp + i].fAver = float(pStudent[_iCount - iTemp + i].iTotal) / 3;
		}
		return pStudent;
	}

	void Show_Studentinfo(CStudent* _pStudent, int& _iCount)
	{
		system("cls");
		for (int i = 0; i < _iCount; ++i)
		{
			cout << "이름: " << _pStudent[i].szName << endl;
			cout << "국어 점수: " << _pStudent[i].iKor << endl;
			cout << "영어 점수: " << _pStudent[i].iEng << endl;
			cout << "수학 점수: " << _pStudent[i].iMath << endl;
			cout << "총점: " << _pStudent[i].iTotal << endl;
			cout << "평균: " << _pStudent[i].fAver << endl;
			cout << "====================================================" << endl;
		}
	}
};

class 부분만 긁어 온 것이다.

새로 더 큰 용량의 동적할당을 받아서 복사해 넣어주고

이전의 동적할당 받은것을 delete 해주는 방식인데

 

비효율적인거 같다.

728x90