Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Can';t将nullptr返回到我的类C++;_C++_Null_Nullptr - Fatal编程技术网

C++ Can';t将nullptr返回到我的类C++;

C++ Can';t将nullptr返回到我的类C++;,c++,null,nullptr,C++,Null,Nullptr,在我的类中的方法中,我正在检查一个值是否为0以返回nullptr,但是我似乎不能这样做 Complex Complex::sqrt(const Complex& cmplx) { if(cmplx._imag == 0) return nullptr; return Complex(); } 我得到的错误是:无法将'nullptr'从'std::nullptr_t'转换为'Complex' 我现在意识到,nullptr用于指针,但是,我的对象不是指针,

在我的类中的方法中,我正在检查一个值是否为0以返回
nullptr
,但是我似乎不能这样做

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

    return Complex();
}
我得到的错误是:
无法将'nullptr'从'std::nullptr_t'转换为'Complex'


我现在意识到,
nullptr
用于指针,但是,我的对象不是指针,有没有办法将其设置为null或类似的值?

您返回的是
Complex
,它不是指针。要返回
nullptr
,返回类型应为
Complex*

注意到您的编辑-以下是您可以做的:

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;
}
可以这样称呼:

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

正如错误所述,
nullptr
不能转换为您的类型
Complex
。您可以做的是(a)返回一个
Complex*
(或者更好的是,返回一个智能指针),并测试
nullptr
,以查看函数是否有一个非平凡的结果,或者(b)使用类似于库的方法来设计函数,使其可能没有有效的对象可返回

事实上,Boost.Optional的文档甚至给出了一个
double sqrt(double n)
函数的示例,它不应该定义为负数
n
,与您的示例类似。如果您可以使用Boost,那么示例如下

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);
}
boost::可选复合体::sqrt(const复合体和cmplx)
{
如果(cmplx.\u imag==0)
//未初始化的值。
返回boost::可选();
//或者,做一些计算。
return boost::可选(这里有一些参数);
}

有些可能会有帮助。

将返回类型设置为Complex*可能是因为您没有在此处返回指针。你想要复杂的*而不是复杂的。同意这个方法。您不必担心内存泄漏,也不需要添加boost。