目前正在编译我的set.cpp文件(我们必须根据set.h文件和test_set.cpp制作该文件(使用g ++编译器,我不断遇到以下警告:
set.cpp: In member function âvoid set::remove(const set::value_type&)â:
set.cpp:30: warning: comparison between signed and unsigned integer expressions
set.cpp: In member function âbool set::contains(const set::value_type&) constâ:
set.cpp:50: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âset set_union(const set&, const set&)â:
set.cpp:65: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âset set_intersection(const set&, const set&)â:
set.cpp:76: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âset set_difference(const set&, const set&)â:
set.cpp:90: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âbool is_subset(const set&, const set&)â:
set.cpp:104: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âbool operator==(const set&, const set&)â:
set.cpp:118: warning: comparison between signed and unsigned integer expressions
set.cpp: In function âstd::ostream& operator<<(std::ostream&, const set&)â:
set.cpp:131: warning: comparison between signed and unsigned integer expressions
我不确定这些是什么意思,并且想知道如何解决这个问题。
您收到的警告很可能来自 for 循环:
例:
void set::remove(const value_type& entry)
{
for(int i = 0; i < used; i++) //the comparison in question is on this line
{
if(data[i] == entry)
{
data [i] = data [used - 1];
used --;
return;
}
}
}
语句:i < used
正在比较i
,这是一个int
,used
我假设它是无符号的类型。
如果您查看警告中指定的每个行号,我相信它们都对应于函数中的 for 循环。
修复这些警告的最简单方法是将int
替换为您用于used
的任何类型。
例如,如果used
是并且unsigned int
则您的 for 循环将变为:
void set::remove(const value_type& entry)
{
for(unsigned int i = 0; i < used; i++)
{
/*...*/
}
}
在没有看到您的头文件的情况下,我假设used
被定义为unsigned int
。在循环中,您将i
定义为int
,从而导致警告。
负值计算结果为无符号整数中的大正数,因此比较两者可能会导致意外结果。快速的解决方案是将i
的所有用法更改为unsigned int
或用于used
的任何实际类型。