Gernot Frisch wrote:
Hi,
when Do I need the:
a a::operator+(a _1);
and when the
a operator+(a _1, a _2)
??
The first is a member function, while the second is not.
The difference is as follows:
Assume
class A
{
public:
A( int i ) : m_i( i ) {}
private:
int m_i;
}
That is: there is a class where objects can implicitely be constructed
from an int.
Now assume you want to write an op+ to add 2 A objects. You do this
as member function
class A
{
....
A operator+( const A& Arg ) { .... }
};
Now what can you do with it?
You can eg. write
A ObjA( 5 );
A ObjB( 7 );
A Result;
Result = ObjA + ObjB;
No problem. But you can also write
Result = ObjA + 7;
Why? Because the compiler can use the constructor to first convert 7
into an A object and then use op+ to perform the addition.
But can you also write
Result = 7 + ObjA;
And the answer is: No. Because 7 is an int, and there is no op+ for
an int which takes an A object.
This seems illogical and it can be cured by making op+ a non member
function
A operator+( const A& lhs, const A& rhs ) { ... }
Now the compiler can use this operator as long as there is one A
object on either side of the '+'. The other one will be converted
to an A object if necessary.
--
Karl Heinz Buchegger
kb******@gascad.at