警告:有符号和无符号整数表达式之间的比较 [英] Warning: Comparison between signed and unsigned integer expression

查看:185
本文介绍了警告:有符号和无符号整数表达式之间的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在codepad.org上运行以下代码,但出现此错误。 在成员函数'double Xchange :: getprice(std :: string)'中:
第87行:警告:有符号和无符号整数表达式之间的比较

I am running hhe following code on codepad.org and I am getting this error. "In member function 'double Xchange::getprice(std::string)': Line 87: warning: comparison between signed and unsigned integer expressions"

这是我的代码:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Xchange
{
public:
    Xchange();//does nothing (?)

    double getprice(string symbol);

private:
    vector <Stock> stocks;
};

double Xchange::getprice(string symbol)
{
    for(int i=0; i < stocks.size(); i++) {
        if(stocks[i].getsymbol()==symbol) {
            return stocks[i].getprice();
        }
    }

    return -1; //means not found
}


推荐答案

for(int i=0; i < stocks.size(); i++)

i 是一个有符号整数, stocks.size ()未签名。您可以使用 std :: size_t ,或者,如果要更加精确,请使用 vector< Stock> :: size_type

i is a signed integer, stocks.size() is unsigned. You can use std::size_t, or, if you want to be more precise, use the vector<Stock>::size_type.

for(vector<Stock>::size_type i=0; i < stocks.size(); i++) { .... }

此警告试图防止的问题是负号到无符号转换会产生大量的转换,很可能不是您想要的转换。除此之外,有符号整数的数值范围与相同大小的无符号整数的数值范围不同。

The problem this warning is trying to prevent is that a negative signed to unsigned conversion yields a large number and is most likely not what you want. Besides that, the numerical range of a signed integer is no the same as that of an unsigned one of the same size.

请参见C++类型以获取更多信息。

See C++ types for more information.

请注意,这在C ++ 11中更容易:

Note that this is easier in C++11:

for(const auto& stock : stocks)
{
    if(stock.getsymbol()==symbol) //added getsymbol "()"
    {
        return stock.getprice();
    }
}

这篇关于警告:有符号和无符号整数表达式之间的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆