Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Другие языки > ООП на Rust


Автор: Majestio 10.3.2018, 14:29
Приветствую!

Решил ознакомится с Rust, но не заметил там "нативной" поддержки ООП. Тем не менее, конструкции языка позволяют применять инструментарий ООП. Нашел https://rustycrate.ru/%D0%BE%D0%B1%D1%83%D1%87%D0%B5%D0%BD%D0%B8%D0%B5/2017/06/11/oop-in-rust.html#polimorfizm-podtipov про это. Но увы, цельного примера я там не нашел, все расписывалось кусками. А хотелось бы в качестве резюме - полноценный пример.

Кому не лениво, и кто в теме, прошу составленный https://ideone.com/4pxz4m перевести на Rust:

Код
#include <iostream>
#include <vector>

// *****************************************************************************

class Figure {
  public:
    virtual double Area() = 0;
    void PrintName() {
      std::cout << "Фигура = " << Name() << " ";
    }
  private:
    virtual std::string Name() = 0;
};

// *****************************************************************************

class Rectangle: public Figure {
  public:
    explicit Rectangle(double h, double w): H(h), W(w) {}
    double Area() override {
      return H*W;     
    }
  private:
    double H,W;
    std::string Name() override {
      return "Прямоугольник";
    }
};

// *****************************************************************************

class Square: public Rectangle {
  public:
    explicit Square(double l): Rectangle (l,l) {}
  private:
    std::string Name() override {
      return "Квадрат";
    }
};

// *****************************************************************************

class Ellipse: public Rectangle {
  public:
    explicit Ellipse(double a, double b): Rectangle (a,b) {}
    double Area() override {
      return Rectangle::Area()*3.1415;     
    }
  private:
    std::string Name() override {
      return "Эллипс";
    }
};

// *****************************************************************************

int main() {
  std::vector<Figure*> V;
  V.push_back(new Rectangle(2,3));
  V.push_back(new Square(4));
  V.push_back(new Ellipse(2,3));
  for(const auto &i:V) {
    i->PrintName();
    std::cout << ", площадь: " << i->Area() << std::endl;
    delete i;
  }
  return 0;
}


Пока не пойму, как в Rust реализовать абстрактный класс, виртуальный метод, и как работать с перекрытием методов?

Автор: Majestio 11.3.2018, 12:45
Кому будет интересно - вот одно из решений:

Код

    use std::io::stdin;
    use std::io::BufRead;
    use std::io::BufReader;
     
    mod figures {
     
        pub trait Figure {
            fn area(&self) -> f64;
            fn printName(&self) {
                print!("Figure = {} ", self.name());
            }
            fn name(&self) -> &'static str;
        }
     
        pub struct Rectangle {
            w: f64,
            h: f64,
        }
     
        impl Rectangle {
            pub fn new(width: f64, height: f64) -> Rectangle {
                Rectangle { w: width, h: height }
            }
        }
     
        impl Figure for Rectangle {
            fn name(&self) -> &'static str {
                "Rectangle"
            }
            fn area(&self) -> f64 {
                self.h * self.w
            }
        }
     
        pub struct Square {
            rectangle: Rectangle,
        }
     
        impl Square {
            pub fn new(size: f64) -> Square {
                Square { rectangle: Rectangle { w: size, h: size } }
            }
        }
     
        impl Figure for Square {
            fn name(&self) -> &'static str {
                "Square"
            }
            fn area(&self) -> f64 {
                self.rectangle.area()
            }
        }
     
        pub struct Ellipse {
            rectangle: Rectangle,
        }
     
        impl Ellipse {
            pub fn new(a: f64, b: f64) -> Ellipse {
                Ellipse { rectangle: Rectangle { w: a, h: b } }
            }
        }
     
        impl Figure for Ellipse {
            fn name(&self) -> &'static str {
                "Ellipse"
            }
            fn area(&self) -> f64 {
                self.rectangle.area() * 3.1415
            }
        }
    }
     
    fn main() {
        use figures::{Figure, Rectangle, Square, Ellipse};
        let v: [&Figure; 3] = [
            &Rectangle::new(2.0, 3.0),
            &Square::new(4.0),
            &Ellipse::new(2.0, 3.0)
            ];
        for i in v.iter() {
            i.printName();
            println!(", area: {}", i.area());
        }
    }

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)