212: Build a class representing a university student with private data members for name, ID, and a static data member for the total number of students. Implement getter and setter functions for name and ID, and a static getter function to retrieve the total number of students. Use default constructors
// Build a class representing a university student with private data members for
// name, ID, and a static data member for the total number of students. Implement
// getter and setter functions for name and ID, and a static getter function to
// retrieve the total number of students. Use default constructors
#include <iostream>
using namespace std;
class Student
{
private:
static unsigned int count;
string name, id;
public:
// constructor
// Student() : name(""), id("") { count++; }
// Student(string x, string y) : name(x), id(y) { count++; }
// set data
void setData();
// print
void printStudent();
static int printTotal_students();
};
unsigned int Student ::count = 0;
int Student ::printTotal_students() { return count; }
void Student ::setData()
{
cout << "Enter name: ";
getline(cin >> ws, name);
cout << "Enter id: ";
getline(cin >> ws, id);
count++;
}
void Student ::printStudent()
{
cout << "Name: " << name << endl;
cout << "Id: " << id << endl;
}
// user-defined functions
string input(string x)
{
string temp;
cout << x;
cin >> temp;
return temp;
}
int main()
{
Student students[10];
// input students
for (int i = 0; i < 10; i++)
{
char temp;
cout << "Enter # to exit or any other key to continue: ";
cin >> temp;
if (temp == '#')
{
break;
}
students[i].setData();
cout << endl;
}
system("cls");
// print students
for (int i = 0; i < Student::printTotal_students(); i++)
{
cout << "Student # " << i + 1 << ':' << endl;
students[i].printStudent();
cout << endl;
}
cout << "Total no. of Students: " << Student::printTotal_students() << endl;
return 0;
}
Comments
Post a Comment