Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.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++ 如果通过值失败进行比较测试(C+;+;)_C++_Object - Fatal编程技术网

C++ 如果通过值失败进行比较测试(C+;+;)

C++ 如果通过值失败进行比较测试(C+;+;),c++,object,C++,Object,我当前的项目太长,无法在这里发布,然而,这是一行代码,它产生了一种非常奇怪的行为,至少在我看来是这样。我使用clip对象来存储相对较短的字符串(35中使用的最大大小),但是在start中处理负值时,该条件失败 我尝试在clip.length()前面添加(const int),但输出不变: 你知道这是什么意思吗?我在Ubuntu 14.04上使用G++ void Cut ( const int start, const int stop ) { if (start > clip.leng

我当前的项目太长,无法在这里发布,然而,这是一行代码,它产生了一种非常奇怪的行为,至少在我看来是这样。我使用
clip
对象来存储相对较短的字符串(35中使用的最大大小),但是在
start
中处理负值时,该条件失败

我尝试在
clip.length()前面添加
(const int)
,但输出不变:

你知道这是什么意思吗?我在Ubuntu 14.04上使用G++

 void Cut ( const int start, const int stop )
 { if (start > clip.length() ) cout << "start: " << start << " > " << clip.length() << endl;

  ...
 }
void Cut(常数整数开始,常数整数停止)

{if(start>clip.length())cout很可能
length()
返回
unsigned int
,因此另一个参数
signed int
也被转换为unsigned,然后进行比较

这是所谓的常用算术转换的一部分。参见标准:

表达式[expr]

否则,如果具有无符号整数类型的操作数的秩大于或等于 另一个操作数类型的秩,有符号整数类型的操作数应转换为 具有无符号整数类型的操作数的类型


原因在于这种比较:

if (start > clip.length()) {
您正在比较有符号和无符号。我建议将两个操作数更改为具有相同的类型,例如:

if (start > static_cast<int>(clip.length())) {

使用g++,尝试使用
-Wall
,甚至可能使用
-Wextra

添加
(const int)
应该可以解决这个问题。缺少a,我们帮不了你。为什么要投否决票?请自由建议我如何改进我的帖子,谢谢。你的编译器没有警告过你比较有符号和无符号整数吗?你需要启用更多的警告。我对编程很陌生,老实说,我一直在公然避免警告,但我不知道在查找错误3小时左右后,我现在学习了我的课程,因为我没有启用警告。这是更深层次的答案。如果编译器警告已打开,OP可能会在发布之前发现错误。@user43389如果你喜欢这个答案,为什么不接受它?
test.cpp:8:13: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]