问题
I'm starting out with structures, and I'm having problems dynamically allocating my structure array. I'm doing what I see in my book and on the internet, but I can't get it right.
Here's both full error messages:
C2512: 'Record' : no appropriate default constructor available
IntelliSense: no default constructor exists for class "Record"
#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;
}
回答1:
The error is quite clear. By the time you are trying to allocate an array:
Record *room = new Record[5];
a default constructor, i.e. Record::Record()
, must be implemented so that 5 instances of Record
can be created:
struct Record
{
...
Record() : average(0.0) { }
Record(int s[], double a) { ... }
};
Also note that dynamic allocation is something you want to avoid as much as possible in C++ (except the situations when you have really good reason for it). In this case it would be more reasonable to use an std::vector
instead:
std::vector<Record> records(5);
来源:https://stackoverflow.com/questions/19850765/error-c2512-no-appropriate-default-constructor-available-not-classes