NEED SOME HELP PLEASE
Mar 31, 2016 at 4:44am UTC
When your program is run, you will be given 2 sets of 3 inputs which you should use to create the appropriate objects: a string representing the type ("student" or "faculty"), a string for the name of the person, and either a double GPA for a student, or a string representing a department for a faculty.
I need help with creating pointers to the appropriate objects and store them both in a single vector called my_list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
class Person
{
public :
Person(string name);
virtual string toString() = 0;
protected :
string name;
};
void printList(vector<Person*> list);
Person::Person(string name)
{
this ->name = name;
}
class Student : public Person
{
public :
Student(string name, double GPA);
string toString();
private :
double GPA;
};
Student::Student(string name, double GPA) : Person(name)
{
this ->GPA = GPA;
}
string Student::toString()
{
stringstream ss;
ss << "Name: " << name << endl;
ss << "GPA: " << GPA << endl;
return ss.str();
}
class Faculty : public Person
{
public :
Faculty(string name);
string toString();
private :
string department;
};
int main()
{
printList(my_list);
return 0;
}
void printList(vector<Person*> list)
{
for (int i = 0; i < list.size(); i++)
{
cout << list[i]->toString();
}
}
Mar 31, 2016 at 12:25pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13
std::string type;
std::string name;
std::cin >> type;
if ( "foo" == type ) {
double gaz;
std::cin >> name >> gaz;
mylist.push_back( new Foo( name, gaz ) );
}
else if ( "bar" == type ) {
std::string gaz;
std::cin >> name >> gaz;
mylist.push_back( new Bar( name, gaz ) );
}
Could you use smart pointers in your vector? Raw pointers are such a chore to rinse clean.
Topic archived. No new replies allowed.