C/C++: Perimeter and area of rects. Volume of cuboids

Viewed 2183

I want to calculate area and perimeter of rects using the following code:

    rect a;
    a = ( -----
          !   !
          -----a );
std::cout << a.area() << std::endl;
std::cout << a.perimeter() << std::endl;

For this purpose I crafted the following class:

class rect
{
public:
    rect():w(0), h(2) {}
    rect& operator - () { w += 0.5f; return *this; }
    rect& operator - (rect&) { w += 0.5f; return *this; }
    rect& operator -- (int a) { w += a; return *this; }
    rect& operator -- () { w += 1; return *this; }
    rect& operator ! () { h += 0.5f; return *this; }
    void clear() { w = 0; h = 2; }
    int area() { return w * h; }
    int perimeter() { return 2 * w + 2 * h; }
    int width() { return w; }
    int height() { return h; }
private:
    float w;
    float h;
};

Here are some usage examples:

#include <iostream>

int main()
{
    rect a;

    a = ( -----
          !   !
          -----a );

    std::cout << a.area() << std::endl;
    std::cout << a.perimeter() << std::endl;
    std::cout << a.width()  << std::endl;
    std::cout << a.height() << std::endl;

    std::cout << std::endl;

    a.clear();

    a = ( ----------
          !        !
          !        !
          !        !
          !        !
          ---------a );

    std::cout << a.area() << std::endl;
    std::cout << a.perimeter() << std::endl;
    std::cout << a.width()  << std::endl;
    std::cout << a.height() << std::endl;

    return 0;
}

Here are my questions:

  1. Can it be done without involving any floating point arithmetic? (indeed, it is an integer grid)
  2. Can it be generalized on a 3D case? I.e:

    cuboid b;
    b = (  ---------
          /        /!
         ! -------! !
         !        ! !
         !        ! !
         !        !/
         ---------b );
    
    std::cout << b.volume() << std::endl;
    
2 Answers
Related