I want to create an operator function that takes one integer and one double as parameters and returns true if the integer is lesser than the double, else it will return false. I came from a programming language named Ada, where such tasks would be executed in this manner but doesn't seem to be the same with C .
Is it possible to do this in C and if so what's really wrong with my code?
This is the errors I get:
12 | bool operator <(int const lhs,
| ^~~~~~~~
This is my code:
#include <iostream>
using namespace std;
bool operator <(int const lhs,
double const rhs)
{
if (double(lhs) < rhs)
{
return true;
}
return false;
}
int main()
{
int lhs {};
double rhs {};
cin >> lhs >> rhs;
if (!rhs < lhs)
{
cout << "False";
}
}
In my main program I tried outputting "False" if rhs < lhs = false
CodePudding user response:
Assuming you meant lhs < rhs
, rather than rhs < lhs
, you'll need to provide a function for the less comparison, rather than try to overload the operator<
with non-user defined types.
#include <iostream>
using std::cin;
using std::cout;
// Thwart implicit conversion.
template <typename T, typename T2>
bool is_less(T const, T2 const) = delete;
template <>
bool is_less(int const lhs,
double const rhs)
{
if (double(lhs) < rhs)
{
return true;
}
return false;
}
int main()
{
int lhs {};
double rhs {};
cin >> lhs >> rhs;
// Note: changed (rhs, lhs) to (lhs, rhs).
if (!is_less(lhs, rhs))
{
cout << "False\n";
}
}
CodePudding user response:
You may overload operators for user-defined types as for example classes or enumerations.
As for this statement
cin >> lhs > rhs;
then due to the operator precedence it is equivalent to
( cin >> lhs ) > rhs;
So in fact you are trying to compare an object of the type std::istream with an object of the type double. But such an operator is not defined.
Also it seems in the condition of the if statement
if (!rhs < lhs)
there is a typo.
Maybe you mean
if (!( rhs < lhs ) )