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
|
//The purpose of program is to implement a class Person with two fields name and age and a class
//class car with three fields: model, pointer to the owner and a pointer to the driver.
#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 Person::increment_age(); // is inside the class body so the prefix Person:: is not needed.
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::Car(string m); //Same as Person:: prefix
void Car::set_driver(Person* p) {driver = p;}
void Car::set_owner(Person* p) {owner = p;}
void print() const;
};
Car::Car(string m){ model = m;}
void Car::set_owner(Person* p){*owner = *p;}
void Car::print() const{
cout << model << endl;
cout << "Driver: "; driver->print();
cout << "Owner: "; owner->print();}
int main()
{
vector<Person*> people;
const int PERSON_SZ = 6;
char * names[] = {"Linda", "Jeffrey", "Sue", "Chad", "Wendy", "Denny"};
int ages[] = {39, 34, 42, 49, 38, 48};
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[] = { "Porsche", "Lambourgini", "Corvette" };
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;
}
|