为什么int加上uint会返回uint? [英] Why int plus uint returns uint?

查看:182
本文介绍了为什么int加上uint会返回uint?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int plus unsigned int返回unsigned int。应该这样吗?

int plus unsigned int returns an unsigned int. Should it be so?

考虑以下代码:

#include <boost/static_assert.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/type_traits/is_same.hpp>

class test
{
    static const int          si = 0;
    static const unsigned int ui = 0;

    typedef BOOST_TYPEOF(si + ui) type;
    BOOST_STATIC_ASSERT( ( boost::is_same<type, int>::value ) ); // fails
};


int main()
{
    return 0;
}


推荐答案

如果是应该是你的意思是我的编译器是否符合标准:

If by "should it be" you mean "does my compiler behave according to the standard": yes.

C ++ 2003:第5条第9款:

C++2003: Clause 5, paragraph 9:


许多期望算术或枚举类型操作数的二元运算符会以类似的方式产生转换并产生
结果类型。目的是产生一个通用类型,它也是结果的类型。
这种模式称为通常的算术转换,定义如下:

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:


  • blah

  • 否则, blah

  • 其他, blah ,......

  • 否则,如果任一操作数是无符号的,则另一个操作数将转换为无符号。

  • blah
  • Otherwise, blah,
  • Otherise, blah, ...
  • Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

如果应该是,那么你的意思是如果没有这个世界会变得更好:我没有能力回答这个问题。

If by "should it be" you mean "would the world be a better place if it didn't": I'm not competent to answer that.

这篇关于为什么int加上uint会返回uint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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