Hello every body,
This is an example of class II tutorial in this website:
struct {
string product;
float price;
} a, b, c;
a = b + c;
The code above can be lead to compiler error.
This example is related to overloading operators,
I don't understand, does it mean that if we want to use operators we have to define them firstly in the classes and then use them?
Better say I don't understand the logic behined overloading operators.
Many thanks in advance
does it mean that if we want to use operators we have to define them firstly in the classes
Appropriate operators are predefined for intrinsic types and many standard library types as well. Otherwise, however, the answer is yes. If you want to use an operator on custom (class/struct) types, then you must tell you compiler what it means to use this operator in the context of your class/struct.
A contrived example:
1 2 3 4 5 6 7 8 9 10 11
class Integer {
int value;
public:
Integer(int i) : value(i) {}
// addition operator for your class
Integer operator+(Integer i) { return Integer(value + i.value); }
// conversion operator for your class: to convert a variable of this type to int type
operatorint() { return value; }
};