I want to learn template and operator overloading with the purpose : compare length of vector / integer.
ex. (2,5) > 5 ex. (1,0) < (5,2)
This is my template :
template<class T, class U>
void vectorCmp(T x, U y)
{
cout<<"Call Function Template"<<endl;
// operator overloading
if(x>y)
cout<<x<<endl;
else if(y>x)
cout<<y<<endl;
else if(x==y)
cout<<"The length is equal"<<endl;
}
And this is my Vector class :
class Vector
{
// operator overloading
friend bool operator>(Vector & v1, Vector & v2);
friend bool operator>(Vector & v, int l);
friend bool operator>(int l, Vector & v);
friend ostream & operator<<(ostream & os, Vector & v);
friend ostream & operator<<(ostream & os, int l);
private:
int x;
int y;
public:
Vector(int x, int y)
{
cout<<"Call Vector Constructor"<<endl;
this->x = x;
this->y = y;
}
~Vector()
{
cout<<"Call Vector Destructor"<<endl;
}
};
And below is definition of friend function :
bool operator>(Vector & v1, Vector & v2)
{
cout<<"Call operator overloading"<<endl;
if(sqrt(pow(v1.x,2)+pow(v1.y,2))>sqrt(pow(v2.x,2)+pow(v2.y,2)))
return true;
else
return false;
}
bool operator>(Vector & v, int l)
{
cout<<"Call operator overloading"<<endl;
if(sqrt(pow(v.x,2)+pow(v.y,2))>l)
return true;
else
return false;
}
bool operator>(int l, Vector & v)
{
cout<<"Call \'>\'operator overloading"<<endl;
if(sqrt(pow(v.x,2)+pow(v.y,2))<l)
return true;
else
return false;
}
ostream & operator<<(ostream & os, Vector & v)
{
os<<"Call \'<<\' operator overloading"<<endl;
os<<"The biggest length is "<<sqrt(pow(v.x,2)+pow(v.y,2))<<endl;
return os;
}
ostream & operator<<(ostream & os, int l)
{
os<<"Call \'<<\' operator overloading"<<endl;
os<<"The biggest length is "<<l<<endl;
return os;
}
There are three situations when comparing length of vector/ integer:
-> vector / integer
-> vector / vector
-> integer / vector
and there are two situations to cout:
-> cout << vector
-> cout << integer
Below is my main function :
int main()
{
int len = 10;
Vector vec1(12,3);
Vector vec2(2,5);
vectorCmp(len,vec1);
vectorCmp(vec2,len);
vectorCmp(vec1,vec2);
return 0;
}
When I compiles, error happens !
error: ambiguous overload for 'operator<<' (operand types are 'std::basic_ostream' and 'int')
I cannot understand why overloading "<<" with integer is error
Thanks for solving my question !