So I just created a struct that makes a rectangle. the struct itself look likes this
struct _rect
{
//bottom left vertex
int x = 0;
int y = 0;
// width and height
int width = 0;
int height = 0;
//top right vertex
int y2 = y height;
int x2 = x width;
};
//init rect
_rect rect01;
rect01.x = rect01.y = 50;
rect01.width = rect01.height = 200;
in the main cpp when I want to create an instance of it I just want to enter bottom left x and y, plus width and height and I want it to calculate top right vertex by itself, is there a way to assign x2 and y2 their values without manuly doing so ?
CodePudding user response:
You should create a specific class:
class Rect
{
public:
Rect(int x, int y, unsigned int width, unsigned int height)
: x(x), y(y), width(width), height(height)
{}
int x() { return x; }
int y() { return y; }
int top() { return y height; }
int right() { return x width; }
private:
int x;
int y;
unsigned int width;
unsigned int height;
};
That give you the possibility to do the computation you need in the class methods. You can also create setters and more getters if you want.
CodePudding user response:
Below is the complete working example:
#include <iostream>
class Rect
{
public:
//parameterized constructor
Rect(int px, int py, unsigned int pwidth, unsigned int pheight): x(px), y(py), width(pwidth), height(pheight), x2(x width), y2(y height)
{
};
//getter so that we can get the value of x2
int getX2()
{
return x2;
}
//getter so that we can get the value of y2
int getY2()
{
return y2;
}
private:
int x = 0;
int y = 0;
unsigned int width = 0;
unsigned int height = 0;
int x2 = 0, y2 = 0;
};
int main()
{
//create Rect instance
Rect r(50, 50, 200, 200);
//lets check if x2 and y2 were calculate correctly
std::cout<<"x2 is: "<< r.getX2()<<std::endl;
std::cout<<"y2 is: "<< r.getY2()<<std::endl;
}
The output of the above program can be seen here.