-2

I am trying to Implement the class Rectangle which consists of two Points representing opposing corners of the rectangle. The Point struct has already been declared in the header file. I do not know how to use the x,y in the struct class in the Rectangle Class.

The is the .h file:

struct Point {
    double x, y;
};

// Define your class below this line
class Rectangle
{
public:
    Rectangle(double p.x, double p.y, double w, double h);
    double getArea() const;
    double getWidth() const;
    double getHeight() const;
    double getX() const;
    double getY() const;

    void setLocation(double x, double y);
    void setHeight(double w, double h);
private:
    Point p;
    double width;
    double height;

};

In the .cpp I initialize like:

Rectangle::Rectangle(double p.x, double p.y, double w, double h)
:(p.x),(p.y), width(w), height(h)
{

}
Hidden
  • 15
  • 3
  • Create constructor with two arguments for Point and call it in initializer list of Rectangle constructor – Maxwe11 Nov 23 '14 at 22:21
  • Your code doesn't match your description. You said you where going to define it by two points representing opposite corners. You've actually used one point and two dimensions (width and height). – Persixty Nov 23 '14 at 22:22

1 Answers1

2

You can make a constructor for point like so:

struct Point {
    double x, y;
    Point(double xx, double yy): x(xx), y(yy){}
};

Then change the constructor in rectangle to:

Rectangle::Rectangle(double x, double y, double w, double h)
:p(x,y), width(w), height(h)
{   
}

If you are using c++11 you have an additional option too. Because Point is a Aggregate structure you can initialize it as juanchopanza suggests like so:

Rectangle::Rectangle(double x, double y, double w, double h)
:p{x,y}, width(w), height(h)
{   
}

The benefit here is that you don't need to add a constructor to the Point struct if you choose this approach.

Community
  • 1
  • 1
shuttle87
  • 15,466
  • 11
  • 77
  • 106