I am facing a problem to parameterize a constructor with array user input.
My question is:
Create a class named
Student
and make a constructor with parameter likeStudent(int i, string n, double s)
there are three private variables namedint id, string name, double score
and useint getID(),string getName(),double getScore()
to taking input and usevoid print()
for output. You need to define all the member functions including constructors.Then define 3 students in the main function. Get the values of the objects and output the details.
My code is given below:
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
class Student
{
private :
int id;
string name;
double score;
public:
Student();
Student (int i, string n, double s)
{
id = i;
name = n;
score = s;
}
int getID()
{
cin >> id;
return id;
}
string getName()
{
getline(cin,name);
return name;
}
double getScore()
{
cin >> score;
return score;
}
void print()
{
cout << id << " " << name << " " << score << " " << endl;
}
};
int main()
{
Student stuArr[10];
int i;
for(i = 0; i < 3; i++)
{
cout << "Student " << i + 1 << endl;
cout << "Enter ID: " << endl;
stuArr[i].getID();
cout << "Enter name: " << endl;
stuArr[i].getName();
cout << "Enter marks: " << endl;
stuArr[i].getScore();
}
for(i = 0; i < 3; i++)
{
stuArr[i].print();
}
return 0;
}
But my code doesn't work. It doesn't show any output. It builds, but doesn't give any output.
Currently the code is not even compilable, you should get an error: undefined reference to Student::Student()
. Your constructor is missing body. Change Student();
to Student() {}
.
try to give values in the class itself, I mean while declaring the name,...etc variables. and see if that gives you any output else, if it works then try to create objects manually without looping if it works then most probably your looping thing has some issue.
BTW, I am a python and dart student, I learnt C++ in my first year of graduation.(Not so good as I am with python and dart)!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.