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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include <string>
#include <iostream>
class Person
{
private:
std::string name;
int age {};
double weight {};
public:
Person(const std::string&, int, double);
Person();
void setName(const std::string&);
void setAge(int);
void setWeight(double);
std::string getName() const;
int getAge() const;
double getWeight() const;
};
Person::Person() {}
Person::Person(const std::string& x, int y, double z) : name(x), age(y), weight(z) {}
void Person::setName(const std::string& nameOne) {
name = nameOne;
}
void Person::setAge(int ageOne) {
age = ageOne;
}
void Person::setWeight(double weightOne) {
weight = weightOne;
}
std::string Person::getName() const {
return name;
}
int Person::getAge() const {
return age;
}
double Person::getWeight() const {
return weight;
}
//Initiating PersonData class
class PersonData {
private:
// Variables for the class. Person to temporarily store, person list array, and capacity and size
Person *personList {};
int capacity {}, size {};
public:
// Constructor to set the person class + size and capacity
PersonData(const Person& x) {
add(x);
}
~PersonData() {
delete[] personList;
}
void resizeArray() {
// double the capacity
capacity = (capacity == 0) ? 2 : capacity * 2;
// dynamically create new array
auto tempArray {new Person[capacity]};
// Copy contents of old array to new array
// tempArray - pointer to new array, arrayPtr = pointer to old array
for (int counter = 0; counter < size; ++counter)
tempArray[counter] = personList[counter];
//Deallocate to prevent memory leaks
delete[] personList;
personList = tempArray;
}
void add(const Person& x) {
// Check if the array is the same size as it's capacity-- in other words, is the array full?
// resizeCopy() function makes more room in the array.
if (size >= capacity)
resizeArray();
// We have room to add the integer, so let's do it
// add the integer num to the end of the array and increase size by 1
personList[size++] = x;
}
void listPersons() {
for (int i = 0; i < size; ++i) {
std::cout << "Name: " << personList[i].getName() << '\n';
std::cout << "Age: " << personList[i].getAge() << '\n';
std::cout << "Weight: " << personList[i].getWeight() << "\n\n";
}
std::cout << "Capacity of the array: " << capacity << '\n';
std::cout << "Records in the array: " << size << '\n';
}
};
int main()
{
Person personOne("John", 22, 140.6);
PersonData person1(personOne);
//person1.listPersons();
person1.add(personOne);
Person personTwo("Mike", 55, 147.6);
person1.add(personTwo);
person1.listPersons();
}
|