Domanda

In my method in my class, I'm checking if a value is 0 to return nullptr, however I can't seem to do that.

Complex Complex::sqrt(const Complex& cmplx) {
    if(cmplx._imag == 0)
        return nullptr;

    return Complex();
}

The error I'm getting is: could not convert 'nullptr' from 'std::nullptr_t' to 'Complex'

I realize now, that nullptr is for pointers, however, my object is not a pointer, is there a way for me to set it to null or something similar?

È stato utile?

Soluzione

You are returning Complex, which is not a pointer. In order to return nullptr, your return type should be Complex*.

Noticed your edit - here's what you can do:

bool Complex::sqrt(const Complex& cmplx, Complex& out) {
    if(cmplx._imag == 0)
    {
        // out won't be set here!
        return false;
    }

    out = Complex(...); // set your out parameter here
    return true;
}

Call it like this:

Complex resultOfSqrt;
if(sqrt(..., resultOfSqrt))
{ 
    // resultOfSqrt is guaranteed to be set here
} 
else
{
    // resultOfSqrt wasn't set
} 

Altri suggerimenti

Well, as the error states, nullptr is not convertible to your type Complex. What you can do is (a) return a Complex* (or better yet, a smart pointer), and test for nullptr to see whether the function had a non-trivial result or perhaps (b) use a library like Boost.Optional to design your function in such a way that it might not have a valid object to return.

In fact, Boost.Optional's documentation even gives the example of a double sqrt(double n) function, which shouldn't be defined for negative n and is similar to your example. If you can use Boost, an example would be like

boost::optional<Complex> Complex::sqrt(const Complex& cmplx) 
{
    if (cmplx._imag == 0)
        // Uninitialized value.
        return boost::optional<Complex>();

    // Or, do some computations.
    return boost::optional<Complex>(some parameters here);
}

Some related discussion that might be helpful.

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