initializing float in a class

J

john smith

Hi,

I am trying to initialize a float in a class.

For example:

class ABC{

public:


private:
static const float = 3.3;

};

The compiler does not like that, and I don't know how to declare and define
a float that has class scope only.

Thanks in advance for your help.
 
M

Mike Wahler

john smith said:
Hi,

I am trying to initialize a float in a class.

For example:

class ABC{

public:


private:
static const float = 3.3;

};

The compiler does not like that, and I don't know how to declare and define
a float that has class scope only.

Only static constant integer types can be initialized
inside the class body. You also failed to give the
'float' object a name.

class ABC
{
public:

private:
static const float f;
};

const float ABC::f(3.3f);



I recommend preferring type 'double' over 'float' unless
you have a compelling reason to use the latter. 'double'
gives you much better precision.

-Mike
 
M

Mike Hewson

john said:
Hi,

I am trying to initialize a float in a class.

For example:

class ABC{

public:


private:
static const float = 3.3;

'static const float' is a type but you have no identifier.

Anyway I think only integrals are allowed for 'static const'.
 
I

Ioannis Vranos

Mike said:
Anyway I think only integrals are allowed for 'static const'.


Yes you are right. Here is also what VC++ 2003 and 2005 Beta say about it:


C:\c>cl /clr temp.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 13.10.3077 for .NET
Framework
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

temp.cpp
temp.cpp(4) : error C2864: 'x' : only const static integral data members
can be
initialized inside a class or struct

C:\c>


C:\c>cl /clr temp.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 14.00.40904
for Microsoft (R) .NET Framework version 2.00.40607.16
Copyright (C) Microsoft Corporation. All rights reserved.

temp.cpp
temp.cpp(4) : error C2864: 'ABC::x' : only static const integral data
members ca
n be initialized within a class

C:\c>
 
U

Ulrich Achleitner

if you need a const static float attribute in your class,
initialize it in the class's implementation file:

const float ClassName::floatAttributeName = 2.2f;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,197
Messages
2,571,038
Members
47,633
Latest member
BriannaLyk

Latest Threads

Top