In the first Classes (II) example of C++ tutorial, the code shows an operator being defined (lines 18-23). The example shows one Cvector parameter (Cvector param), but in the main () function, two added values are passed as a variable to c (c=a+b). How is the operator taking these two values if it only takes one parameter under the operator + definition?
Overloaded operators are just all other functions. Member operators have the this pointer as implicit argument.
Try to see if the following example helps:
#include <iostream>
#include <string>
usingnamespace std;
struct S
{
string name;
S ( string name ) : name ( name ) {}
voidoperator + ( const S &other ) // member operator
{
cout << this->name << " . operator+ ( " << other.name << " )\n";
}
void m ( const S &other ) // member function
{
cout << this->name << " . m ( " << other.name << " )\n";
}
};
voidoperator - ( const S &a, const S &b ) // external operator
{
cout << "operator- ( " << a.name << ", " << b.name << " )\n";
}
void f ( const S &a, const S &b ) // external function
{
cout << "f ( " << a.name << ", " << b.name << " )\n";
}
int main()
{
S first ( "first" ), second ( "second" );
first + second;
first . operator+ ( second );
first . m ( second );
first - second;
operator- ( first, second );
f ( first, second );
return 0;
}
output:
first . operator+ ( second )
first . operator+ ( second )
first . m ( second )
operator- ( first, second )
operator- ( first, second )
f ( first, second )
Think + as a function called 'operator+' which can be called using a syntax which differs from normal function calls
I can't thank you enough for you detailed explanation. Finally understand it!!! The speed and efficiency of you explanation is second to none!!!! Thanks again!!!