1) 구현 성공 code

 

#include <iostream>
#include <string>
using namespace std;
class Dept
{
int size;
int* scores;
public:
Dept(int size) {
this->size = size;
scores = new int[size];
}
Dept(const Dept& dept) {
this->size = dept.size;
scores = new int[dept.size];
for (int i = 0; i < dept.size; i++)
this->scores[i] = dept.scores[i]; // 깊은 복사 생성자를 생성
}
~Dept() { delete[]scores; };
int getSize() { return size; }
void read() {
cout << "10개 점수 입력 >>";
for (int i = 0; i < size; i++)
{
cin >> scores[i];
}
}
bool isOver60(int index) {
if (scores[index] > 60)
return true;
else
return false;
}
};
int countPass(Dept &dept) {
int count = 0;
for (int i = 0; i < dept.getSize(); i++) {
if (dept.isOver60(i)) count++;
}
return count;
}
int main() {
Dept com(10);
com.read();
int n = countPass(com);
cout << "60점 이상은 " << n << "명";
}
view raw cp5_12.cpp hosted with ❤ by GitHub

 

 

2) 복사 생성자가 생성되지 않으면, 같은 공간을 향하게 되어서 메모리 오류 생기게 된다. 

메모리 오류가 생기지 않게 하려면 깊은 복사 생성자를 만들거나 해야함  

위의 코드에서 "int n = countPass(com);" 부분이 복사 생성자가 호출되는 코드 부분이다. 

 

 

3) 복사 생성자를 제거하고도 실행오류가 없게 하려면 참조 연산자를 사용해주면 된다.

#include <iostream>
#include <string>
using namespace std;
class Dept
{
int size;
int* scores;
public:
Dept(int size) {
this->size = size;
scores = new int[size];
}
//Dept(const Dept& dept) {
// this->size = dept.size;
// scores = new int[dept.size];
// for (int i = 0; i < dept.size; i++)
// this->scores[i] = dept.scores[i];
//}
~Dept() { delete[]scores; };
int getSize() { return size; }
void read() {
cout << "10개 점수 입력 >>";
for (int i = 0; i < size; i++)
{
cin >> scores[i];
}
}
bool isOver60(int index) {
if (scores[index] > 60)
return true;
else
return false;
}
};
int countPass(Dept &dept) {
int count = 0;
for (int i = 0; i < dept.getSize(); i++) {
if (dept.isOver60(i)) count++;
}
return count;
}
int main() {
Dept com(10);
com.read();
int n = countPass(com);
cout << "60점 이상은 " << n << "명";
}

+ Recent posts