I’m just starting my own Windows API wrapper and I’ve run into an unfamiliar topic while rewriting a structure to include C++ features.
I’m turning this:
typedef struct _RECT {
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT, *PRECT;
into
#define RECT_POS 1
#define RECT_SIZE 2
typedef struct WrapperRect // RECT
{
WrapperRect(); // all 0
WrapperRect (const double, const double, const double, const double, bool = RECT_POS); // initalize with tl pos and either br pos or size
bool set (const double, const double, const double, const double, bool = RECT_POS); // set tl pos and either br pos or size
bool pos (const double, const double); // set tl pos
bool size (const double, const double); // set size
WrapperRect & operator= (const WrapperRect &); // assign another rect
bool operator== (const WrapperRect &); // check for equality (pos+size)
bool operator!= (const WrapperRect &); // check for inequality (pos+size)
bool operator> (const WrapperRect &); // check for tl pos greater
bool operator< (const WrapperRect &); // check for tl pos less
bool operator>= (const WrapperRect &); // check for tl pos greater equal
bool operator<= (const WrapperRect &); // check for tl pos less equal
WrapperRect & operator+ (const POINT &); // move down/right
WrapperRect & operator- (const POINT &); // move up/left
WrapperRect & operator+= (const POINT &); // move down/right
WrapperRect & operator-= (const POINT &); // move up/left
double l, left, x; // left
double r, right; // right
double t, top, y; // top
double b, bottom; // bottom
double w, width; // width
double h, height; // height
} Rect, rect; // allow more convenient names
My only problem is that if the user were to say
Rect myRect;
myRect.right = 50;
it will set the right side, but won’t be able to change the aliases for the right side, or the width.
I don’t want the members to be private either because I want the
cout << myRect.x;
syntax rather than the annoying
cout << myRect.getX();
syntax.
Is there any way to achieve this, or must I use get functions?
edit:
I really wasn’t thinking when I wrote this, I’ve added some return values (>.>) and changed the double in operator+ etc to a point. I’m starting to try the possibilities before I accept one.
It is quite bad practice to expose your data members. It is also really bad practice to have multiple copies of the exact same information inside your classes. It is both inefficient and bug-prone.
You definitely need to use accessor functions.
That being said, you don’t need to have getX(); – just x() would be fine.
If you’re really set on avoiding function syntax, something like this would be ok I guess:
Then you could use
r.xin a safe fashion though you are still somewhat exposing your implementation.