[英]Can't return nullptr to my class C++
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. 在我的类中的方法中,我正在检查值是否为0以返回
nullptr
,但是我似乎无法做到这一点。
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'
我得到的错误是:
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? 我现在意识到,
nullptr
用于指针,但是,我的对象不是指针,有没有办法让我将它设置为null或类似的东西?
You are returning Complex
, which is not a pointer. 你正在返回
Complex
,它不是指针。 In order to return nullptr
, your return type should be Complex*
. 要返回
nullptr
,您的返回类型应为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
}
Well, as the error states, nullptr
is not convertible to your type Complex
. 好吧,正如错误所述,
nullptr
不能转换为您的类型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. 你可以做的是(a)返回一个
Complex*
(或者更好的是,一个智能指针),并测试nullptr
以查看该函数是否具有非平凡的结果,或者可能(b)使用像Boost.Optional这样的库来以这样一种方式设计你的函数,使它可能没有有效的对象返回。
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. 事实上,Boost.Optional的文档甚至给出了一个
double sqrt(double n)
函数的例子,它不应该为负n
定义,并且与你的例子类似。 If you can use Boost, an example would be like 如果你可以使用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);
}
Some related discussion that might be helpful. 一些相关的讨论可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.