gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:52:46 25 4
gpt4 key购买 nike

我有这个代码:

#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 += ba = a + b 不同,因为前者构造将结果类型转换为 a 的类型。 Reference .但我认为这在 C++ 中并不重要,因为我们总是可以这样做:

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

与 Java 不同,无需担心可能会丢失精度警告。需要在 C++ 中对此进行引用。

现在如果我们假设 name += age; 扩展为 name = string (name + age); 那么代码也不应该编译,因为 name + 年龄不合法。

最佳答案

您需要使用 -Wconversion 标志(我不清楚为什么它不包含在 -Wall 中)另请参阅 Options to Request or Suppress Warnings更多细节。当我添加该标志时,我在使用 gcc 时看到以下警告:

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

我们可以看到确实operator +=确实支持 char,因此转换后的值确实被添加到 name 的末尾,它根本没有忽略该操作。在 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 ) ) ;

您示例中的 operator + 失败的原因在 answer 中有很好的说明。 ,基本上模板函数不会执行转换,因此需要与 const/volatile 限定符 可能的异常(exception)完全匹配。

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 - 为什么在使用 += 将整数连接到字符串时 g++ 不发出警告/错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20381036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com