now this code also student + student, then whats the different between 1st code with 3rd code? if in my main function i have code: studentA = studentA + studentB
which operator function will be called? First one or third one?
1 needs to be a member of student, and you should be taking all your parameters by const reference. Also, your this. is incorrect, it should be this->.
As for your question I would say the first one would be called...but that's just me.
Your first operator changes the semantics of the + operator.
The + operator should not modify either operand. (That is what the += operator is for.)
When dealing with a class, you often have the choice of specifying member operators or non-member operators. Both are equivalent when taking operands of the same type.
member
1 2 3 4 5 6 7 8 9
struct point
{
double x;
double y;
point(): x( 0.0 ), y( 0.0 ) { }
point( double x, double y ) x( x ), y( y ) { }
point operator + ( const point& rhs ) const;
};
non-member
1 2 3 4 5 6 7 8 9
struct point
{
double x;
double y;
point(): x( 0.0 ), y( 0.0 ) { }
point( double x, double y ) x( x ), y( y ) { }
};
point operator + ( const point& lhs, const point& rhs );
If you want to mix types, say, "pt1 = 4 + pt2", or somesuch, then only the kind where the rhs operand is a different type may be member operators. The lhs operand operators must be non-member functions.
1 2 3 4 5 6 7 8 9 10
struct point
{
...
point operator + ( double rhs ) const; // handles things like: pt + 5.3
};
point operator + ( double lhs, const point& rhs ) // handles things like: 5.3 + pt
{
return rhs + lhs;
}
In the case of commutative functions like +, you can simply define the non-member function in terms of the member function, as I did in the example.
oh..the reply giving lots of info thanks ...
but i have a question about Duoas reply..
i dun really understand about member and non-member function..
if i have a class point how my non-member function retrieve the data?
For example i using the same class as ur class point just change it to class not struct:
1 2 3 4 5
point operator+(double lhs, const point rhs){
rhs.x = rhs.x+lhs;
rhs.y = rhs.y+lhs;
return rhs;
}
then how my rhs get y and x? since x and y is private.