可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I've tried on a few different forums and can't seem to get a straight answer, how can I make this function return the struct? If I try 'return newStudent;' I get the error 'No suitable user-defined conversion from studentType to studentType exists.'
// Input function studentType newStudent() { struct studentType { string studentID; string firstName; string lastName; string subjectName; string courseGrade; int arrayMarks[4]; double avgMarks; } newStudent; cout << "\nPlease enter student information:\n"; cout << "\nFirst Name: "; cin >> newStudent.firstName; cout << "\nLast Name: "; cin >> newStudent.lastName; cout << "\nStudent ID: "; cin >> newStudent.studentID; cout << "\nSubject Name: "; cin >> newStudent.subjectName; for (int i = 0; i < NO_OF_TEST; i++) { cout << "\nTest " << i+1 << " mark: "; cin >> newStudent.arrayMarks[i]; } newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST ); newStudent.courseGrade = calculate_grade (newStudent.avgMarks); }
回答1:
Here is an edited version of your code which is based on ISO C++ and which works well with G++:
#include <string.h> #include <iostream> using namespace std; #define NO_OF_TEST 1 struct studentType { string studentID; string firstName; string lastName; string subjectName; string courseGrade; int arrayMarks[4]; double avgMarks; }; studentType input() { studentType newStudent; cout << "\nPlease enter student information:\n"; cout << "\nFirst Name: "; cin >> newStudent.firstName; cout << "\nLast Name: "; cin >> newStudent.lastName; cout << "\nStudent ID: "; cin >> newStudent.studentID; cout << "\nSubject Name: "; cin >> newStudent.subjectName; for (int i = 0; i < NO_OF_TEST; i++) { cout << "\nTest " << i+1 << " mark: "; cin >> newStudent.arrayMarks[i]; } return newStudent; } int main() { studentType s; s = input(); cout <<"\n========"<< endl << "Collected the details of " << s.firstName << endl; return 0; }
回答2:
You have a scope problem. Define the struct before the function, not inside it.
回答3:
studentType newStudent() // studentType doesn't exist here { struct studentType // it only exists within the function { string studentID; string firstName; string lastName; string subjectName; string courseGrade; int arrayMarks[4]; double avgMarks; } newStudent; ...
Move it outside the function:
struct studentType { string studentID; string firstName; string lastName; string subjectName; string courseGrade; int arrayMarks[4]; double avgMarks; }; studentType newStudent() { studentType newStudent ... return newStudent; }
回答4:
As pointed out by others, define studentType outside the function. One more thing, even if you do that, do not create a local studentType instance inside the function. The instance is on the function stack and will not be available when you try to return it. One thing you can however do is create studentType dynamically and return the pointer to it outside the function.