将double赋给std :: string - 没有编译错误? [英] Assign double to std::string -- no compile error?

查看:316
本文介绍了将double赋给std :: string - 没有编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么编译器不会抱怨这段代码:

Why isn't the compiler complaining about this code:

#include <string>
#include <iostream>

int main()
{
   std::string a;
   a = 2.3;
   std::cout << "A:" << a << std::endl;
   return 0;
}

GCC,MSVC似乎并不关心这一点,$

GCC, MSVC don't seem to be concerned about this at all, even though it is clearly wrong and doesn't actually work anyway!

输出结果是:

A:

在我的程序中导致未检测到的错误。

OUCH ! Lead to an undetected error in my program.

推荐答案

std :: string operator = 需要一个字符。当您通过值向函数传递参数(即运算符)时,复制初始化。在复制初始化中,标准转化(也称为隐式转换)可能用于转换值。在这种情况下,您的double被默认转换为char,以便它可以在 operator = 中使用。

std::string has an overload for operator= that takes a character. When you pass an argument to a function by value (i.e, an operator), copy initialization occurs. In copy initialization, standard conversions, also known as an "implicit conversion", may be used to the convert the value. In this case, your double is being silently converted to a char so that it may be used in operator=.

对于GCC, -Wall -Wextra -pedantic 将不会显示诊断。您可以尝试 -Wfloat-conversion ,它由 -Wconversion 启用。示例:

For GCC, -Wall -Wextra -pedantic will not make a diagnostic appear. You can try -Wfloat-conversion, which is enabled by -Wconversion. Example:

main.cpp:11:10: warning: conversion to 'char' alters 'double' constant value 
[-Wfloat-conversion]
        a = 3.2;

或者,使用括号强制缩小转换错误。

Alternatively, use braces to force a narrowing conversion error.

s = {4.3};
// warning: narrowing conversion of '4.2e+1' from 'double' to 'char' inside { } 
// [-Wnarrowing]

这篇关于将double赋给std :: string - 没有编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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