2013-04-09 107 views
-2

到明天代码工作好,但知道它给出了一个奇怪的错误.. 没有可用的默认构造函数...
我真的不明白这个错误。而且这是第一次体验与这种类型的错误..我已经搜索的问题,但对构造的讨论是先进的水平.. 我是中级,, .. 请帮助检查我的代码.. !!!构造错误。(奇怪的错误)

// 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; 
} 
+0

你真的可以通过删除所有不相关的代码来改善这个问题。 – juanchopanza 2013-04-09 12:08:41

+0

你是对的juanchopanza,但函数'fetch_id()'和'fetch_name()'是重要的,因为他试图改变结构的数据。 – Zaiborg 2013-04-09 12:10:42

+0

当代码运行良好时,它现在也应该这样做。如果你不想表达什么是明天的状态,你可以告诉今天的变化。 – harper 2013-04-09 12:13:28

回答

5

这是因为你的结构包含常量数组。它们必须在构造函数初始化列表中显式初始化。

由于这些常量成员变量,编译器无法为您生成默认构造函数,所以您必须自己创建一个构造函数。

实际上,我认为你会在代码后期试图分配给它们时错误地使数组不变,因为它们是不变的。

删除const部分的成员数组声明,它应该都会更好。

+0

谢谢你..得到它.. :) – 2013-04-11 10:34:46

+0

好的我已经完成了.. 谢谢大家.. – 2013-04-11 16:24:57

0

一些简单的问题......为什么你使用2维字符数组,为什么不是std::string而不是? cin的事情是,你没有控制输入的长度,所以你会很快得到缓冲区溢出。 soo long zap

+0

是的,我会尽力..谢谢指出这.. – 2013-04-11 10:36:02