문제

구조로 시작하고 구조 배열에 동적으로 할당 된 문제가 있습니다. 나는 내 책과 인터넷에서 내가 보는 것을하고 있지만 그것을 올바르게 얻을 수는 없습니다.

전체 오류 메시지는 다음과 같습니다.

C2512 : '레코드': 사용 가능한 적절한 기본 생성자 없음

IntellIsense : 클래스 "레코드"에는 기본 생성자가 없습니다.

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

const int NG = 4; // number of scores

struct Record
{
    string name;  // student name
    int scores[NG];
    double average;

    // Calculate the average
    // when the scores are known
    Record(int s[], double a)
    {
        double sum = 0;

        for(int count = 0; count != NG; count++)
        {
            scores[count] = s[count];
            sum += scores[count];
        }

        average = a;
        average = sum / NG;
    }
};

int main()
{
    // Names of the class
    string names[] = {"Amy Adams", "Bob Barr", "Carla Carr",
                      "Dan Dobbs", "Elena Evans"};

    // exam scores according to each student
    int exams[][NG]= {  {98, 87, 93, 88},
                        {78, 86, 82, 91},
                        {66, 71, 85, 94},
                        {72, 63, 77, 69},
                        {91, 83, 76, 60}};

    Record *room = new Record[5];


    return 0;
}
도움이 되었습니까?

해결책

오류는 매우 명확합니다. 배열을 할당하려고 할 때까지 :

Record *room = new Record[5];

기본 생성자, 즉 Record::Record(), 5 개의 인스턴스를 위해 구현되어야합니다 Record 만들 수 있습니다 :

struct Record
{
    ...
    Record() : average(0.0) { }
    Record(int s[], double a) { ... }
};

또한 동적 할당은 C ++에서 가능한 한 많이 피하고 싶은 것입니다 (정말 좋은 이유가있는 상황 제외). 이 경우 사용하는 것이 더 합리적입니다. std::vector 대신에:

std::vector<Record> records(5);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top