C++ 질문

조회수 667회

문제가 정수 10개를 입력받아서 60점이상이 몇개인지 출력하는 간단한 문제인데요. 제가 잘못한게 뭔지 잘 모르겠어요.... 보시고 혹시 이 부분 이상하다거나, 이렇게 짜면 더 좋겠다거나 하는 것 있으면 알려주셨으면 감사하겠습니다.

#include <iostream>
using namespace std;

class Dept {
    int size;
    int *scores;
public:
    Dept(int size) {
        this->size = size;
        scores = new int[size];
    }
    ~Dept() { if(scores) delete[]scores; }
    Dept(Dept &dept);
    int getSize() { return size; }
    void read();
    bool isOver60(int index);
};
Dept::Dept(Dept &dept) {
    this->size = dept.size;
    this->scores = new int[dept.size];
}
void Dept::read() {
    cout << size << "개 정수 입력>>";
    for (int i = 0; i < size; i++)
        cin >> scores[i];
}
bool Dept::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 << "명";
}

이미지

왜 0명으로 되는지 모르겠어요....

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기
    countPass(com);
    

    main에서 countPass를 호출하는 시점에 (Dept dept) 매개변수로 인해 복사생성자가 호출됩니다.

    그런데 복사생성자가 아래와 같이 heap memory에 array를 할당하는 코드만 되어 있기 때문에 실제 값은 복사되지 않고 있습니다.

    Dept::Dept(Dept &dept) {
        this->size = dept.size;
        this->scores = new int[dept.size];
    }
    

    따라서 원하는 결과를 얻기 위해서는 복사 생성자 구현을 완성하거나, countPass를 call by reference 형태로 변경하면 됩니다.

    간단하게는 아래와 같이 매개변수를 참조자로 변경하면 해결이 됩니다.

    int countPass(Dept &dept)
    
    • (•́ ✖ •̀)
      알 수 없는 사용자
    • 와.....감사합니다! 송유리 2019.1.28 18:30

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)