3.2. Binary operations overload

Lecture



Any binary operation Å can be defined in two ways: either as a component function with one parameter, or as a global (possibly friendly) function with two parameters. In the first case, x Å y means calling x.operator Å (y) , in the second case - calling operator Å (x, y).

· Operations overloaded within a class can only be overloaded with non-static component functions with parameters. The called class object is automatically taken as the first operand.

· Operations that are reloaded outside the scope of a class must have two operands, one of which must have a class type.

Examples

1) class person {...};

class adresbook

{// contains as component data a set of objects of type // person, represented as a dynamic array, list or tree

...

public:

person & operator [] (int); // access to the i-th object

};

person & adresbook:: operator [] (int i) {. . .}

void main ()

{class adresbook persons;

class person record;

...

record = persons [3];

}

2) class person {...};

class adresbook

{// contains as component data a set of objects of type // person, represented as a dynamic array, list or tree

...

public:

friend person & operator [] (const adresbook &, int); // access to the i-th object

};

person & operator [] (const adresbook & ob, int i) {. . .}

void main ()

{class adresbook persons;

class person record;

...

record = persons [3];

}

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "C ++ (C plus plus)"

Terms: C ++ (C plus plus)