You have a simple struct, say:
struct rect
{
int x;
int y;
int width;
int height;
};
And you want to multiply each element by a factor. Is there a more concise way of performing this operation, other than multiplying each member by the value?
Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.
Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures.
No, you cannot define a function within a struct in C. You can have a function pointer in a struct though but having a function pointer is very different from a member function in C++, namely there is no implicit this pointer to the containing struct instance.
Passing of structure to the function can be done in two ways: By passing all the elements to the function individually. By passing the entire structure to the function.
Not really. Programatically obtaining a list of the elements of a struct requires reflection, which C++ does not support.
Your two options are to just give the struct a method that does this the long-winded way and then use that method in all other places, or to manually mimic reflection, for example by giving the struct another element which is an array of pointers to all of its other elements (built within the struct's constructor), and then looping over that to perform the scaling function.
No; there is no way to iterate over the members of a struct.
In this particular case, though, you can accomplish your goal by using an array:
struct rect
{
// actually store the data in an array, not as distinct elements
int values_[4];
// use accessor/mutator functions to modify the values; it is often best to
// provide const-qualified overloads as well.
int& x() { return values_[0]; }
int& y() { return values_[1]; }
int& width() { return values_[2]; }
int& height() { return values_[3]; }
void multiply_all_by_two()
{
for (int i = 0; i < sizeof(values_) / sizeof(values_[0]); ++i)
values_[i] *= 2;
}
};
(note that this example doesn't make much sense (why would you multiply x, y, height and width by two?) but it demonstrates a different way to solve this sort of problem)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With