diff options
| author | Syndamia <kamen@syndamia.com> | 2024-03-07 18:00:02 +0200 |
|---|---|---|
| committer | Syndamia <kamen@syndamia.com> | 2024-03-07 18:00:02 +0200 |
| commit | a2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f (patch) | |
| tree | b44282a01417c35f47f543ca61ccc2de2e8dbb40 /week03/Exercise5.cpp | |
| parent | c4efdf0a5b9af3d70d75f4ab642305d44e27ba1f (diff) | |
| download | oop-2023-solutions-a2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f.tar oop-2023-solutions-a2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f.tar.gz oop-2023-solutions-a2c7c3ac1fb6e3c877f58f2bab1754f4d93e522f.zip | |
[w3] Solved exercises 5-7
Diffstat (limited to 'week03/Exercise5.cpp')
| -rw-r--r-- | week03/Exercise5.cpp | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/week03/Exercise5.cpp b/week03/Exercise5.cpp new file mode 100644 index 0000000..28721a4 --- /dev/null +++ b/week03/Exercise5.cpp @@ -0,0 +1,96 @@ +#include <cstring> + +struct Car { +private: + char* model; + unsigned int doors; + unsigned int seats; + +public: + Car() { + model = nullptr; + doors = 0; + seats = 0; + } + Car(const char* model, unsigned int doors, unsigned int seats) { + this->model = nullptr; + setModel(model); + setDoors(doors); + setSeats(seats); + } + ~Car() { + delete[] model; + } + + const char* getModel() { + return model; + } + void setModel(const char* newModel) { + delete[] model; + model = new char[strlen(newModel) + 1]; + strcpy(model, newModel); + } + + unsigned int getDoors() { + return doors; + } + void setDoors(unsigned int newDoorsCount) { + doors = newDoorsCount; + } + + unsigned int getSeats() { + return seats; + } + void setSeats(unsigned int newSeatsCount) { + seats = newSeatsCount; + } + + void CopyDataTo(Car& destination) { + destination.setModel(model); + destination.setDoors(doors); + destination.setSeats(seats); + } +}; + +struct TrafficJam { +private: + Car* cars; + int size; + int lastIndex; + + void resize() { + Car* newCars = new Car[size * 2]; + for (int i = 0; i < size; i++) { + cars[i].CopyDataTo(newCars[i]); + } + delete[] cars; + cars = newCars; + size *= 2; + } + +public: + TrafficJam() { + size = 3; + cars = new Car[size]; + lastIndex = 0; + } + ~TrafficJam() { + delete[] cars; + } + + void AddCar(Car& car) { + if (lastIndex == size) + resize(); + car.CopyDataTo(cars[lastIndex++]); + } +}; + +int main() { + TrafficJam tj; + + Car c1("Toyota", 4, 5); + Car c2("Ferarri", 2, 2); + + tj.AddCar(c1); + tj.AddCar(c2); +} |
