Class Return Type Overloading
I commonly run into the following situation where I have a data structure which I'd like to have access as follows:
class data {
public:
double error;
double value;
...
}
...
data *outputs;
...
double lastValue = ...;
double someValue = ...;
for (int i开发者_JS百科 = 0; i < n; ++i) {
outputs[i] = someValue; //should be equivalent to outputs[i].value = someValue
outputs[i].error = lastValue - someValue;
}
Currently I just use outputs[i].value =
but, for readability purposes, it actually would make more sense to use (something similar to) the above example (at least from a theory point of view, the code doesn't require maintainability).
I understand that operator= would work for the above situation, but what about a simple access, I'd still have to use outputs[i].value. What would be the best solution to this for readability for both the conceptual design and also without causing headaches for the programmer.
You can add an assignment operator overload to data
:
class data {
public:
double error, value;
void operator=(double d) { value = d; }
};
Though, to be honest, I think this would be rather confusing. It depends on how you intend to use it, of course, but given your example, I think it would be cleaner to add a constructor for the class:
class data {
public:
double error, value;
data(double value_arg, double error_arg)
: value(value_arg), error(error_arg) { }
};
used as:
outputs[i] = data(someValue, lastValue - someValue);
精彩评论