gpt4 book ai didi

c++ - 错误 C2512 : no appropriate default constructor available (not classes)

转载 作者:行者123 更新时间:2023-11-30 04:12:22 25 4
gpt4 key购买 nike

我刚开始使用结构,但在动态分配我的结构数组时遇到了问题。我正在做我在书中和互联网上看到的事情,但我做不对。

以下是完整的错误信息:

C2512:“记录”:没有合适的默认构造函数可用

IntelliSense:类“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;
}

最佳答案

错误很明显。当您尝试分配数组时:

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);

关于c++ - 错误 C2512 : no appropriate default constructor available (not classes),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19850765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com