Simple (I hope) c++ question - cout an object of a user defined class

  • Thread starter Thread starter KeithLovell
  • Start date Start date
K

KeithLovell

Guest
I am not sure if this is the right forum for this question but it is the nearest that I have been able to find.

This code was adapted from code supplied in the book c++ for dummies. I would like to be able to output the student id number in the cout statements in main() but cannot figure out how to make it compile (using Visual Studio)

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int nextStudentId = 1000; // first valid student id
class StudentId
{
public:
// default constructor assigns student-ids sequentially
StudentId()
{
value = nextStudentId++;
cout << "Take next student id " << value << endl;
}
// int constructor allows user to assign id
StudentId(int id)
{
value = id;
cout << "Assign student id " << value << endl;
};
~StudentId()
{
cout << "Destructing student id " << value << endl;
}
protected:
int value;
};

class Student
{
public:
Student(const char* pName, int ssId)
: name(pName), id(ssId)
{
cout << "Constructing student " << pName << endl;
name = pName;
semesterHours = 0;
gpa = 0.0;
StudentId id(ssId);
}
Student(const char* pName)
// : name(pName), id(ssId)
{
cout << "Constructing student " << pName << endl;
name = pName;
semesterHours = 0;
gpa = 0.0;
// StudentId id;
}
~Student()
{
cout << "Destructing student " << name << endl;
}
public:
string name;
int semesterHours;
double gpa;
StudentId id;
};


int main(int nNumberofArgs, char* pszArgs[])
{
// create a couple of students
cout << "Next student id " << nextStudentId << endl;
Student* pS = new Student("Jack", 1234);

cout << "This mesage from main after Jack " << pS->name << *(pS->id) << endl; // would like to add the student id here.

Student* pS2 = new Student("Scruffy");
cout << "This message from main after Scruffy " << pS2->name << endl; // and here

delete pS;
delete pS2;
cout << "Next student id " << nextStudentId << endl;



// wait until user is ready before terminating program
// to allow user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}


Can anyone guide me?

Continue reading...
 
Back
Top