C++ 构造函数错误。。(奇怪的错误)
直到明天,代码工作正常,但知道它会给出一个奇怪的错误。。 没有可用的默认构造函数..C++ 构造函数错误。。(奇怪的错误),c++,C++,直到明天,代码工作正常,但知道它会给出一个奇怪的错误。。 没有可用的默认构造函数.. 我真的不明白这个错误。。此外,这是第一次遇到此类错误。。我搜索了一些问题,但是关于构造函数的讨论是高级的。。 我是中级,,。。 请帮助检查我的代码 // error.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <st
我真的不明白这个错误。。此外,这是第一次遇到此类错误。。我搜索了一些问题,但是关于构造函数的讨论是高级的。。 我是中级,,。。 请帮助检查我的代码
// error.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Student
{
const char name[6][11];
const int id[5];
};
void fetch_id(Student& s, const int size)
{
for (int i = 0; i < size; i++)
{
cout << "roll no of student: " << i+1 << endl;;
cin >> s.id[i];
}
}
void fetch_name(Student& s, const int size)
{
for (int j = 0; j < size; j++)
{
cin.getline(s.name[j], 10);
cout <<"name of student: " << j+1 << endl;
}
}
void display_name(Student s, const int size)
{
cout << "Student Names Are" << endl;
for (int i = 0; i < size; i++)
{
if ( s.name[i] != '\0' )
cout << s.name[i] << endl;
}
}
void display_id(Student s, const int size)
{
cout << "Roll Numbers Are" << endl;
for (int i = 0; i < size; i++)
{
cout << s.id[i] << " || ";
}
}
int main()
{
const int size = 5;
Student s; // error C2512: 'Student' : no appropriate default constructor available ??
fetch_id(s, size);
display_id(s, size);
cout << '\n';
fetch_name(s, size);
cout << '\n';
display_name(s, size);
system("Pause");
return 0;
}
//error.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
#包括
#包括
使用名称空间std;
体类型
{
常量字符名[6][11];
const int id[5];
};
无效获取id(学生和学生,常量整数大小)
{
对于(int i=0;i 这是因为您的结构包含常量数组。它们必须在构造函数初始值设定项列表中显式初始化
由于这些常量成员变量,编译器无法为您生成默认构造函数,您必须自己生成一个
事实上,我认为您在代码后面尝试分配给数组时错误地将数组设置为常量,这是由于数组是常量而无法完成的
删除成员数组声明中的const
部分,它应该会工作得更好。一些简单的问题…为什么要使用二维字符数组,为什么不使用std::string
?
cin的问题是,您无法控制输入的长度,因此很快就会出现缓冲区溢出。
soo long zap你可以通过删除所有不相关的代码来改善这个问题。你是对的juanchopanza,但是函数fetch_id()
和fetch_name()
是很重要的,因为他试图更改结构的数据。当代码运行良好时,直到现在它也应该这样做。如果你不想知道明天的状态如何,你可以告诉他今天的更改。@Zaiborg,这只会突出显示一个不同的错误。构造函数的问题只需要结构
d定义和main()
中的一行。