Visula Studio 2013 初始化静态浮点型数据在C++类内

本文探讨了在C++中初始化静态常量成员变量的方法,特别是对于浮点型数据的处理。通过示例展示了如何正确地在类声明中初始化整型静态常量,并在源文件中初始化浮点型静态常量,避免编译错误。
class MyClass
{
   private:
     static const int intvalue= 50;
     static const float floatvalue = 0.07f;
 };

如上申请方式导致错误

error C2864: 'MyClass::floatvalue : only static const integral data members can be initialized within a class

1. 尝试使用 static constexpr float floatvalue = 0.5f;

error C4430: 缺少类型说明符 - 假定为 int。注意:  C++ 不支持默认 int	
error C2144: 语法错误:“float”的前面应有“;”	

2.  MyClass.h

class MyClass
{
   private:
     static const int intvalue = 50; // can provide a value here (integral constant)
     static const float floatvalue; // canNOT provide a value here (not integral)
};

MyClass.cpp

const int MyClass::intvalue; // no value (already provided in header)
const float MyClass::floatvalue = 0.07f; // value provided HERE

可以解决如上问题

 

博客参考 https://stackoverflow.com/questions/17566575/how-to-initialize-a-static-const-float-in-a-c-class-in-visual-studio

 

转载于:https://www.cnblogs.com/flyinggod/p/10444832.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值