#c
Вопрос:
Я пробовал этот код, но когда я вызываю функцию-член внутри цикла, он выдает мусорное значение подробностей, а когда я вызываю функцию-член вне цикла, это приводит к ошибке.
#includelt;iostreamgt; #includelt;string.hgt; using namespace std; class student { char name[10]; int id,rollno; public: student(char name[10],int id,int rollno) { strcpy(this-gt;name,name); this-gt;id=id; this-gt;rollno=rollno; coutlt;lt;"the name of the student is:"lt;lt;namelt;lt;endl; coutlt;lt;"the id of the student is:"lt;lt;idlt;lt;endl; coutlt;lt;"the roll no of the student is:"lt;lt;rollnolt;lt;endl; } }; int main() { int id1,rollno1; char name1[10]; for(int i=1;ilt;=2;i ) { coutlt;lt;" enter the detail of the student "lt;lt;ilt;lt;" "lt;lt;endl; coutlt;lt;"enter the name of the student:"; cingt;gt;name1; coutlt;lt;"enter the id of the student:"; cingt;gt;id1; coutlt;lt;"enter the roll no of the student:"; cingt;gt;rollno1; student d[]={student(name1,id1,rollno1)}; d[i].print(); } return 0; }
Ответ №1:
Вот ваш обзор кода.
#include lt;iostreamgt; #include lt;string.hgt; using namespace std; // it is strongly suggested that you don't use the whole header unless your intent is speeding up coding class Student // capitalize classes { char _name[10];// it is ok, however, if you use the lt;stringgt; header, why would you go back to char type? int _id, _rollno; public: Student(char name[10] /* this is just the array's first item passed! */, int id, int rollno) { // Don't use this-gt;, use an underscore for one of the names. // I use underscores for the encapsulated data strncpy_s(_name, name, 9);// a safer version _id = id; _rollno = rollno; cout lt;lt; "nCtor says: "; cout lt;lt; "the name of the student is: " lt;lt; _name lt;lt; endl; cout lt;lt; "the id of the student is: " lt;lt; _id lt;lt; endl; cout lt;lt; "the roll no of the student is: " lt;lt; _rollno lt;lt; endl; cout lt;lt; 'n'; } const char* getName() { return _name; } const int getId() { return _id; } const int getRollNo() { return _rollno; } // unless you overload operatorlt;lt; , you have to make getters for your info, or make it public }; int main() { int id, rollno;// why 1? they won't intersect with the function char name[10]; Student *s[2];//you must make that on the heap; otherwise you need a default constructor for (int i{ 0 }; i lt; 2; i )// start with 0 and make it just lt; { cout lt;lt; "enter the details of the student " lt;lt; i lt;lt; endl;// Why so many spaces? cout lt;lt; "enter the name of the student: "; // add space after the colon cin gt;gt; name;// remember, you're limited to 9 chars n !!! cout lt;lt; "enter the id of the student: "; cin gt;gt; id; cout lt;lt; "enter the roll no of the student: "; cin gt;gt; rollno; //student d[] = { student(name,id,rollno) }; // you can't do this. It's not flexible. // You either assign enough space for the intended number of students in the stack, statically, or // you lett it find more space in the heap = dynamically //this goes to the heap s[i]= new Student( name,id,rollno );// parentheses are well //s[i] = new Student{ name,id,rollno };// initializer list may also do //d[i].print();// what's to print here? It's not POD, cout needs instructions cout lt;lt; "Stored data -gt; Id: " lt;lt; s[i]-gt;getId() lt;lt; ", Name: " // -gt; dereferences the pointer, and s is a pointer now lt;lt; s[i]-gt;getName() lt;lt; ", Roll no: " // or you can dereference it lt;lt; (*s[i]).getRollNo() lt;lt; endl lt;lt; endl; // make some extra space here } return 0; }
Комментарии:
1.
lt;stringgt;
Заголовок объявляетstd::string
, какой код операции не используется. Код OP , однако, используетstrcpy(3)
, который объявлен вlt;string.hgt;
; способ ссылки на «канонический C »lt;string.hgt;
— этоlt;cstringgt;
.2. @Вайнштейн, ты прав. Я не обратил на это внимания.