本文介绍了现在允许为std :: string分配一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

  #include< iostream& 
int main(){
std :: string foo;
foo = -1; //为什么编译器不会抱怨这个?
std :: cout<< 1<< std :: endl;
std :: cout<< foo< std :: endl;
std :: cout<< 2< std :: endl;
}

实际输出(ideone.com C ++ 14模式和GCC 4.8。 4):

<无输出> 




  1. 为什么代码段完全编译?

  2. 注释掉 foo = -1 ,我得到正确的stdout( 1 2 )。编译器使用 foo = -1; 编译会导致后续 cout 失败?


解决方案
  foo = -1; 

解析为 std :: string :: operator =(char) code>因为 -1 int int 可以,在理论上,可以转换为 char



int 不表示有效的 char 时。


$ b

更新

C ++ 11标准(强调我):

必须查阅您的编译器文档以了解它是否允许 char 对象保存负值,如果是,它如何处理这些对象。


Consider the following code snippet:

#include <iostream>
int main() {
    std::string foo;
    foo = -1; // why is the compiler not complaining about this?
    std::cout << "1" << std::endl;
    std::cout << foo << std::endl;
    std::cout << "2" << std::endl;
}

Actual output (both ideone.com C++14 mode and GCC 4.8.4):

<no output>

Questions:

  1. Why did the code snippet compile at all?
  2. Commenting out foo = -1, I get the correct stdout (1 and 2). What has the compiler compiled with foo = -1; that causes the subsequent couts to fail?
解决方案
foo = -1;

resolves to std::string::operator=(char) since -1 is an int and int can, in theory, be converted to a char.

It's not clear to me what the standard says when the int does not represent a valid char. It looks like in your implementation, the program crashes.

Update

From the C++11 Standard (emphasis mine):

It appears that you'll have to consult your compiler's documentation to understand whether it allows char object to hold negative values and, if it does, how does it treat such objects.

这篇关于现在允许为std :: string分配一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:40