Here it is my program. I'm especially worried about the main because I know that one must be careful while instancing vectors of "inherited" objects. The code I have works fine (as far as I can see) but I saw the original program made by my teacher and his implementation of the vector in the main uses new and iterator. I'd like to have some piece of advice on how to improve!
#include <vector>
#include <iostream>
#include <cmath>
class Station {
private:
double x_, y_;
public:
Station(double x, double y) : x_(x), y_(y) { }
Station(const Station & s) : x_(s.x_), y_(s.y_) { }
// dichiarazione funzione globale
friend double dist(const Station & s, const Station & t);
};
class Train {
private:
double vm_;
public:
Train(double vm) : vm_(vm) { }
double getvm() {return vm_; }
virtual double time_of_travel(const Station & s, const Station & t) {
return( dist(s, t)/vm_);
}
};
class Regionale : public Train {
public:
Regionale() : Train(60.) { }
};
class Intercity : public Train {
private:
Station stop_;
public:
Intercity(const Station stop) : stop_(stop), Train(110.) { }
double time_of_travel(const Station & s, const Station & t) {
return( (dist(s, stop_) + dist(stop_, t))/this->getvm());
}
};
double dist(const Station & s, const Station & t) {
return(sqrt(pow(s.x_ - t.x_, 2) + pow(s.y_ - t.y_, 2)));
}
int main() {
Station Milano (0. ,0.);
Station Bergamo (35. ,25.);
Station Piacenza (40. , -45.);
std::cout << dist (Milano, Bergamo) << std::endl;
std::cout << dist (Bergamo, Piacenza) << std::endl;
std::cout << dist (Piacenza, Milano) << std::endl;
Intercity i(Milano);
Regionale r;
std::vector<Train * > v = {&i, &r};
for(auto elem : v) std::cout << elem->time_of_travel(Bergamo, Piacenza) << std::endl;
}
std::in some places inmain()\$\endgroup\$I wrote the program with using namespace stdI'll just pretend I didn't read that ;) \$\endgroup\$