(Operator Overload in Templates) Write a simple function template for predicate
ID: 3626009 • Letter: #
Question
(Operator Overload in Templates) Write a simple function template for predicate function isEqualTo that compares its two arguments of the same type with the equality operator (==) and returns true if they are equal and false otherwise. Use this function template in a program that calls isEqualTo only with a variety of fundamental types. Now write a separate version of the program that calls isEqualTo with a user-defined class type, but does not overload the equality operator. What happens when you attempt to run this program? Now overload the equality operator ( with the operator function ) operator==. Now what happens when you attempt to run this program?Explanation / Answer
please rate - thanks
# include <iostream>
using namespace std;
template <class Type>
bool isEqualTo(Type a ,Type b)
{if(a==b)
return true;
return false;
}
int main ()
{int a=1,b=2,f=2;
double c=3,d=4,e=4;
cout<<"a=1,b=2: "<<isEqualTo(a,b)<<endl;
cout<<"b=2,f=2: "<<isEqualTo(b,f)<<endl;
cout<<"c=3,d=4: "<<isEqualTo(c,d)<<endl;
cout<<"d=4,e=4: "<<isEqualTo(d,e)<<endl;
system("pause");
return 0;
}
-----------------------------------------
recieves an error message--doesn't compile
---------------------------------
# include <iostream>
using namespace std;
class largeintegers
{
public:
largeintegers();
void Input();
bool operator==( largeintegers);
private:
int integer[ 10 ];
int len;
};
void largeintegers::Input()
{string in;
int i,j,k;
cout<<"Enter a number("<<10<<" digits max):";
cin>>in;
for(i=0;in[i]!='';i++);
len=i;
k=0;
for(j=i-1;j>=0;j--)
integer[j]=in[k++]-48;
}
largeintegers::largeintegers( )
{
for ( int i = 0; i <10; i++ )
integer[ i ] = 0;
len=9;
}
bool largeintegers::operator==( largeintegers op2 )
{int i;
if(len!=op2.len)
return false;
for(i=len-1;i>=0;i--)
if(integer[i]!=op2.integer[i])
return false;
return true;
}
template <class Type>
bool isEqualTo(Type a ,Type b)
{if(a==b)
return true;
return false;
}
int main ()
{int a=1,b=2,f=2;
double c=3,d=4,e=4;
largeintegers n1,n2;
cout<<"a=1,b=2: "<<isEqualTo(a,b)<<endl;
cout<<"b=2,f=2: "<<isEqualTo(b,f)<<endl;
cout<<"c=3,d=4: "<<isEqualTo(c,d)<<endl;
cout<<"d=4,e=4: "<<isEqualTo(d,e)<<endl;
n1.Input();
n2.Input();
cout<<"n1,n2: "<<isEqualTo(n1,n2)<<endl;
system("pause");
return 0;
}
------------------------------
works perfectly
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.