Domanda

I am trying to make a method in my user defined class that will compare two lengths and return true if the implicit parameter is greater than the explicit parameter but it keeps saying I cannot use the > symbol and I'm not sure why. Any help would be greatly appreciated.

bool isGreaterThan(English_length&L)
{
if (isGreaterThan(L)>L)
    return true;
else
    return false;

}
È stato utile?

Soluzione 2

I assume that isGreaterThan is a member function and the thing you wanted is:

bool isGreaterThan(English_length&L)
{
if ( *this > L)
    return true;
else
    return false;

}

Comparing the object it is called on with the object being passed as argument. Or simpler:

bool isGreaterThan(English_length&L)
{
    return *this > L
}

Altri suggerimenti

It looks like English_length does not have an overloaded < operator. For more information see here.

Even after you have fixed the problem, your code will result in a stack overflow due to infinite recursion.

You're comparing the result of isGreaterThan (a bool) to an English_length object.

What you probably want is something along these lines:

    class English_length {
    private:
        size_t length;

    public:
        bool isGreaterThan(const English_length& other) const {
            return length > other.length;
        }
    };

Idiomatically, you'll want to overload operator >, instead of defining an isGreaterThan function:

    class English_length {
       ...

       bool operator>(const English_length& other) const { 
           return length > other.length; 
       }           
    }

First of all you wrote a recursive function that will end never

bool isGreaterThan(English_length&L)
{
if (isGreaterThan(L)>L)
    return true;
else
    return false;

}

isGreaterThan calls itself in line

if (isGreaterThan(L)>L)

However the compiler did not allow to run this infinite function because it found an error that there is no defined operator > that compares an object of ty[e bool (it is return type of the call isGreaterThan(L) ) with an object of type English_length

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top