编程语言
首页 > 编程语言> > java – 为什么在使用=将一个整数连接到一个字符串时g不会发出警告/错误

java – 为什么在使用=将一个整数连接到一个字符串时g不会发出警告/错误

作者:互联网

我有这个代码:

#include <iostream>                     
using namespace std; 

int main()                  
{                                                                                    
       string name = "John ";                     
       int age = 32;         
       name += age;    
       cout << name << endl;
       return 0;                                          
}

代码编译成功但在运行时背叛,因为它默默地忽略连接部分并打印:

John

我知道我们需要使用stringstream来完成任务.但为什么上面的代码编译?
因为以下代码:

#include <iostream>
using namespace std;                                                                 

int main()                       
{                                                                                    
       string name = "John ";                              
       int age = 55;                                    
       name = name + age;             
       cout << name << endl;      
       return 0;
} 

适当抛出和错误:

error: no match for ‘operator+’ in ‘name + age’

我从Java中知道a = b与a = a b不同,因为前一个构造将结果类型化为a的类型. Reference.但我不认为这对C来说很重要,因为我们总能做到:

   int a = 1;                                                                       
   float f = 3.33;                                                                  
   a = a + f;

与Java不同,不必担心可能会丢失精确警告.需要在C中引用.

所以,如果我们假设name = age;扩展为name = string(name age);那么代码也不应该仅仅因为姓名年龄不合法而编译.

解决方法:

你需要使用-Wconversion标志(我不清楚为什么它不包含在-Wall中)也可以参见Options to Request or Suppress Warnings了解更多细节.当我添加该标志时,我在使用gcc时会看到以下警告:

 warning: conversion to 'char' from 'int' may alter its value [-Wconversion]
    name += age;  
         ^

我们可以看到operator +=确实支持char,因此转换后的值确实被添加到名称的末尾,它根本不会忽略操作.在C operator +中,std::string是与operator =不同的运算符.

在这个特定情况下:

name += age;

会翻译成这样的东西:

name.operator+=(static_cast<char>(age)) ;

如果我们有一个表达式使用运算符而没有像这样的错误:

name = name + static_cast<char>( age );

会转化为:

operator+( name, static_cast<char>( age ) ) ;

在这个answer中很好地解释了为什么你的示例中的运算符失败的原因,基本上模板函数不会执行转换,因此需要与const / volatile限定符的可能异常完全匹配.

Wconversion更新

gcc有一个带有常见问题解答的Wconversion Wiki,它有点过时但它确实回答了为什么这个检查不包含在-Wall标志中:

Implicit conversions are very common in C. This tied with the fact that there is no data-flow in front-ends (see next question) results in hard to avoid warnings for perfectly working and valid code. Wconversion is designed for a niche of uses (security audits, porting 32 bit code to 64 bit, etc.) where the programmer is willing to accept and workaround invalid warnings. Therefore, it shouldn’t be enabled if it is not explicitly requested.

标签:java,c-2,type-conversion,g,implicit-conversion
来源: https://codeday.me/bug/20190718/1491828.html