Pointers and Vectors
Jan 21, 2012 at 2:26am UTC
I have the following program where I am supposed to Implement a class Person with two fields name and age, and a class Car with three fields the model, a pointer to the owner, and a pointer to the driver. The code is compiling but I'm not getting any output. Any suggestions?
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person
{
private :
string name;
int age;
public :
Person(string n, int a);
string get_name()const ;
int get_age()const ;
void increment_age();
void print()const ;
};
Person::Person(string n, int a){
name = n;
age = a;}
string Person::get_name() const {
return name;}
void Person::increment_age(){
age += 1;}
void Person::print() const {
cout << name << endl;
cout << age << endl;}
class Car
{
private :
string model;
Person *owner;
Person *driver;
public :
Car(string m);
void set_driver(Person* p);
void set_owner(Person* p);
void print()const ;
};
Car::Car(string m){
model = m;}
void Car::set_driver(Person* p){
driver = p;}
void Car::set_owner(Person* p){
owner = p;}
void Car::print() const {
cout << model << endl;
cout << driver->get_name() << endl;
cout << owner->get_name() << endl;}
int main()
{
vector<Person*> people;
const int PERSON_SZ = 4;
char * names[] = {"Jim" , "Fred" , "Harry" , "Linda" };
int ages[] = { 23, 35, 52, 59 };
for (int i = 0; i < PERSON_SZ; i++){
Person *a = new Person(names[i], ages[i]);
people.push_back(a);}
vector<Car*> cars;
const int CAR_SZ = 3;
char * models[] = { "Festiva" , "Ferrarri" , "Prius" };
for (int i = 0; i < CAR_SZ; i++)
{
Car *c = new Car(models[i]);
c->set_driver(people[rand()% (people.size())]);
c->set_owner(people[rand()% (people.size())]);
cars.push_back(c);
}
system("pause" );
return 0;
}
Jan 21, 2012 at 3:30am UTC
The code is compiling but I'm not getting any output. Any suggestions?
you don't get any output since you don't use
cout object to print something.
also you dont release dinamicaly alocated objects.
is this your code?
Topic archived. No new replies allowed.