Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- class Vehicle
- {
- public:
- virtual std::string compareTo(Vehicle* v) = 0;
- };
- class Bicycle : public Vehicle
- {
- public:
- Bicycle() { color_ = "red"; }
- std::string compareTo(Vehicle* v) { return "We're different vehicles."; }
- std::string compareTo(Bicycle* b) { return color_.compare(b->color_) ? "We're different bicycles." : "We're the same bicycle."; }
- private:
- std::string color_;
- };
- class Car : public Vehicle
- {
- public:
- Car() { style_ = "sedan"; }
- std::string compareTo(Vehicle* v) { return "We're different vehicles."; }
- std::string compareTo(Car* c) { return style_.compare(c->style_) ? "We're different cars." : "We're the same car."; }
- private:
- std::string style_;
- };
- int main()
- {
- Vehicle* compareFrom = new Bicycle();
- std::vector<Vehicle*> compareTos;
- compareTos.push_back(new Bicycle());
- compareTos.push_back(new Car());
- std::vector<Vehicle*>::iterator it;
- for (it = compareTos.begin(); it != compareTos.end(); ++it)
- std::cout << compareFrom->compareTo(*it) << std::endl;
- return 0;
- }
- std::string Bicycle::compareTo(Vehicle* v) {
- if (Bicycle* b = dynamic_cast<Bicycle*>(v)) {
- return compareTo(b);
- } else {
- return "We're different vehicles.";
- }
- }
- #include <iostream>
- #include <iomanip>
- #include <string>
- #include <typeinfo>
- struct vehicle {
- virtual bool compare_to(vehicle const& other) const = 0;
- };
- bool vehicle::compare_to(vehicle const& other) const {
- return typeid(*this) == typeid(other);
- }
- struct car : vehicle {
- std::string color;
- car(std::string const& color) : color(color) { }
- bool compare_to(vehicle const& other) const {
- bool result = vehicle::compare_to(other);
- return result and (color == static_cast<car const&>(other).color);
- }
- };
- struct bike : vehicle {
- int spokes;
- bike(int spokes) : spokes(spokes) { }
- bool compare_to(vehicle const& other) const {
- bool result = vehicle::compare_to(other);
- return result and (spokes == static_cast<bike const&>(other).spokes);
- }
- };
- int main() {
- car c1("blue");
- car c2("red");
- bike b1(42);
- std::cout << std::boolalpha;
- std::cout << c1.compare_to(c2) << "n"
- << c1.compare_to(b1) << "n"
- << c1.compare_to(c1) << "n";
- }
- enum Kind {
- HUMAN_POWERED = (0x1 << 0),
- MOTOR_POWERED = (0x1 << 1),
- BICYCLE = (0x1 << 2) | HUMAN_POWERED,
- UNICYCLE = (0x1 << 3) | HUMAN_POWERED,
- CAR = (0x1 << 4) | MOTOR_POWERED
- };
- bool areSameClass (Vehicle const & lhs, Vehicle const & rhs)
- {
- return (lhs->getKind () & rhs->getKind ()) & (HUMAN_POWERED | MOTOR_POWERED);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement