سؤال

أبدأ بالهياكل ، وأواجه مشاكل في تخصيص مجموعة الهيكل الخاصة بي. أفعل ما أراه في كتابي وعلى الإنترنت ، لكن لا يمكنني الحصول عليه بشكل صحيح.

إليك كلتا رسائل الخطأ الكاملة:

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