有符号和无符号整数表达式之间的比较



目前正在编译我的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,这是一个intused我假设它是无符号的类型。

如果您查看警告中指定的每个行号,我相信它们都对应于函数中的 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的任何实际类型。

最新更新