控制到达bool函数中非void函数的结束
Control reaches end of non void function in bool function
这是我目前正在处理的代码,我似乎无法找出一种方法来使这个函数停止抛出"控制达到非无效函数的结束"错误。else语句不应该捕捉if语句没有捕捉到的东西并返回真或假吗?
bool operator == (const MyInt& x, const MyInt& y)
{
if (x.currentSize != y.currentSize)
{
return false;
}
else
{
for (int i = 0; i < x.currentSize; i++)
{
if (x.integer[i] != y.integer[i])
{
return false;
break;
}
else
return true;
}
}
}
如果x.currentsize == 0
和y.currentsize == 0
,那么您将永远不会达到return
语句。
我感觉你打算写下面的代码。请注意,我们只在测试了整个列表后才使用return true
。
bool operator==(const MyInt& x, const MyInt& y)
{
if (x.currentSize != y.currentSize)
return false;
for (int i = 0; i < x.currentSize; i++)
if (x.integer[i] != y.integer[i])
return false;
return true;
}
你必须在第一个else
上放一个return,以防你的方法没有经过for循环,例如,当x.currentSize = 0
同样,你的if
条件总是在第一次迭代后返回一个值,所以你应该这样改变它,这样你就可以检查Array
bool operator == (const MyInt& x, const MyInt& y)
{
if (x.currentSize != y.currentSize)
{
return false;
}
else
{
for (int i = 0; i < x.currentSize; i++)
if (x.integer[i] != y.integer[i])
return false;
return true;
}
}
这种错误的一般原因是代码不好,难以阅读。
按如下方式重写函数
bool operator ==( const MyInt &x, const MyInt &y )
{
if ( x.currentSize == y.currentSize )
{
int i = 0;
while ( i < x.currentSize && x.integer[i] == y.integer[i] ) i++;
return ( i == x.currentSize );
}
return ( false );
}
或者如果integer
是指针或数组,则可以应用标头<algorithm>
中声明的标准算法std::equal
。例如
#include <algorithm>
//...
bool operator ==( const MyInt &x, const MyInt &y )
{
return ( x.currentSize == y.currentSize &&
std::equal( x.integer, x.integer + x.currentSize, y.integer ) );
}
我认为这段代码看起来好多了,不是吗? 相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在c++类上调用void函数
- 在派生函数中指定void*参数
- C++为什么尽管我调用了void函数,它却不起作用
- 如何从void函数输出字符串
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 如何将指针从一个void函数传递到另一个C++
- 为什么全局函数 void showA(A&x) 能够访问 A 类的私有成员?
- 如何将函数<void()>写入管道/套接字对?
- 错误:无法在没有对象的情况下调用成员函数'void Fortest::run()'|
- 标准的大小::函数<void(int&)>类型
- 如何函数<void(字符串消息)>绑定到成员函数?
- 函数void()返回一个值,而不是char或string
- 函数void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha)的用途
- 错误 LNK2019:函数 "void __cdecl Padding(int)" 中引用未解析的外部符号___iob_func
- 我可以有一个~析构函数(void)吗?
- 函数<void(T)> 带有默认参数的参数
- 错误:参数太少,无法函数"void alpha(std::string*,student)"