【问题标题】:Can't return nullptr to my class C++无法将 nullptr 返回到我的 C++ 类
【发布时间】:2013-07-17 23:07:18
【问题描述】:

在我课堂上的方法中,我正在检查值是否为 0 以返回 nullptr,但我似乎做不到。

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

    return Complex();
}

我得到的错误是:could not convert 'nullptr' from 'std::nullptr_t' to 'Complex'

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

【问题讨论】:

  • 设置返回类型为Complex*
  • 可能是因为您没有在此处返回指针。你想要复杂*而不是复杂。

标签: c++ null nullptr


【解决方案1】:

您正在返回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
} 

【讨论】:

  • 同意这个方法。您不必担心内存泄漏,也不需要添加 boost。
【解决方案2】:

好吧,正如错误所示,nullptr 不能转换为您的类型Complex。你可以做的是(a)返回一个Complex*(或者更好的是,一个智能指针),并测试nullptr,看看这个函数是否有一个不平凡的结果,或者(b)使用像@这样的库987654321@ 以这样一种方式设计你的函数,它可能没有一个有效的对象要返回。

事实上,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);
}

一些related discussion 可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2018-05-23
    相关资源
    最近更新 更多