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
|
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <cstdlib>
#include <utility>
#include <iostream>
#include <cstring>
using namespace std;
class TrainRoute
{
private:
string departure;
string destination;
char* trainCode {};
public:
TrainRoute() {}
TrainRoute(const string& dep, const string& dest, const char* train) : departure(dep), destination(dest), trainCode(strcpy(new char[strlen(train) + 1], train)) {}
TrainRoute(const TrainRoute& t) : TrainRoute(t.departure, t.destination, t.trainCode) {}
TrainRoute& operator=(const TrainRoute& t)
{
TrainRoute tr(t);
swap(tr.departure, departure);
swap(tr.destination, destination);
swap(tr.trainCode, trainCode);
return *this;
}
~TrainRoute()
{
delete[] trainCode;
}
friend ostream& operator<<(ostream& os, const TrainRoute& tr);
};
class FreightTrainRoute : public TrainRoute
{
private:
int nbOfWagons {};
float* weightPerWagon {};
public:
FreightTrainRoute() : TrainRoute("", "", "Unknown") {}
FreightTrainRoute(const string& departure, const string& destination, const char* trainCode) : TrainRoute(departure, destination, trainCode) {}
~FreightTrainRoute()
{
delete[] weightPerWagon;
}
void setWeight(int nb, const float* weight) {
nbOfWagons = nb;
if (weightPerWagon)
delete[] weightPerWagon;
weightPerWagon = new float[nbOfWagons];
memcpy(weightPerWagon, weight, nb * sizeof(float));
}
friend ostream& operator<<(ostream& os, const FreightTrainRoute& ftr);
};
ostream& operator<<(ostream& os, const TrainRoute& tr)
{
return os << tr.departure << " " << tr.destination << " " << (tr.trainCode != nullptr ? tr.trainCode : "");
}
ostream& operator<<(ostream & os, const FreightTrainRoute& ftr)
{
os << dynamic_cast<const TrainRoute&>(ftr) << " " << ftr.nbOfWagons << " ";
for (int i = 0; i < ftr.nbOfWagons; ++i)
os << ftr.weightPerWagon[i] << " ";
return os;
}
int main()
{
/*
TrainRoute def;
TrainRoute tr1("dep", "dest", "code");
TrainRoute tr2(tr1);
TrainRoute tr3;
tr3 = tr2;
cout << "def\n";
cout << def << "\n\n";
cout << "tr1\n";
cout << tr1 << "\n\n";
cout << "tr2\n";
cout << tr2 << "\n\n";
cout << "tr3\n";
cout << tr3 << "\n\n";
*/
FreightTrainRoute ftr;
FreightTrainRoute ftr1("dep", "dest", "code");
cout << "ftr\n";
cout << ftr << "\n\n";
cout << "ftr1\n";
cout << ftr1 << "\n\n";
const float weights[4] {2.3, 4.5, 6.7, 8.9};
ftr1.setWeight(4, weights);
cout << "ftr1 set\n";
cout << ftr1 << '\n';
}
|