Domanda

ok so below I have a struct in c++:

typedef struct tagRECTEx{
 int top;
 int bottom;
 int left;
 int right;
 int width=(this->right-this->left);
 int height;

} RectEx;

Now what I would like it to do is that when I declare say RextEx WindowSize; and I assign WindowSize.left=250 and WindowSize.right=300, I want it where WindowSize.width will subtract that for me so when I go and use cout << "Window Width: " WindowSize.width; it will autoamticly subtract right and left which will be 50.

I do not want to do this:

WindowSize.width=(WindowSize.right-WindowSize.left);

I want that to it for me via:

... int width=(this->right-this->left); ...

The only way this will work is if I do this instead:

typedef struct tagRECTEx{
 int top;
 int bottom;
 int left=250;
 int right=300;
 int width=(this->right-this->left);
 int height;

} RectEx;

but I can't have it do that as they will always change.

Can someone please help me with this as I've been trying to find this online on google for the past 5 hours now.

Thank you

È stato utile?

Soluzione

There are several ways of ensuring that width is always "in sync" with the left and right:

  • Making tagRECTEx immutable, and setting the width in the constructor, or
  • Adding setter functions for all your variables, and updating width every time left or right is changed, or
  • Replacing width variable with the width() member function, like this:

int width() {
    return right-left;
}

I prefer this last method, because it is usually more economical, and because it greatly reduces the probability of introducing bugs during maintenance.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top