質問

私は構造から始めており、構造配列を動的に割り当てる問題があります。私は自分の本やインターネットで見たことをやっていますが、それを正しく理解することはできません。

これが両方とも完全なエラーメッセージです:

C2512: 'Record':適切なデフォルトコンストラクターは利用できません

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