首页  

C++ 花括号和括号初始化的区别     所属分类 c 浏览量 608
double doubleValue=9.99;
// 转化 且 丢失精度 9
int a(doubleValue) ;
// error: type 'double' cannot be narrowed to 'int' in initializer list
//  编译错误
// int b{doubleValue}; 

内置类型 编译器有默认的构造函数

变量c的初始化,就是调用了其中的一个构造函数(double)

{}初始化  initializer-list
导致精度降低、范围变窄等  
narrowing conversion 编译器警告


#include "iostream"

int main(){
  double doubleValue=9.99;
  // 转化 且 丢失精度
  int a(doubleValue) ;
  // 9
  std::cout << a << std::endl;
  // error: type 'double' cannot be narrowed to 'int' in initializer list
  //  编译错误
  // int b{doubleValue}; 
  
  int c = static_cast(doubleValue);
  // 9
  std::cout << c << std::endl;
  
  return 0; 
}

上一篇     下一篇
C++11 智能指针

C++类成员初始化

c++ 初始化列表

C++面向对象知识点

c++构造函数

C++ this 指针