Assume the following code:
#include <string>
#include <iostream>
using namespace std;
struct A
{
operator int()
{
return 123;
}
operator string()
{
return string("abc");
}
};
void main()
{
A a;
cout<<(a==123)<<endl;
//cout<<(a==string("abc"))<<endl;
}
First, I compare object a
with an int
variable. Then, I attempt to compare it with a string
variable, but the program files to compile. With the line containing the comparison commented out, it compiles just fine. What is the problem?
You provided the conversion operators for your class to int
as well as std::string
,
That ensures the conversion happens appropriately.
However, for the ==
to work the types being compared must have an ==
defined.
The language provides an implicit ==
for int
type but ==
operator overload for std::string
and hence the error.