• 10
• 10
• 12
• 12
• 14

static const double PI = 3.1415

This topic is 4249 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi, I tried the following: class Math { public: static const double PI = 3.1415; }; But the compiler complains: only static const integral data members can be initialized within a class What is going on? Why can't double be initialized? Any solution? Please help.

Share on other sites
well, you could try this:

const struct{  operator const double() const { return 3.1415; }} PI;

Although, PI is already defined in <cmath>

Share on other sites
class Math{public:static const double PI;};static const double Math::PI = 3.1415;

Share on other sites
Quote:
 Original post by daeridwell, you could try this:*** Source Snippet Removed ***Although, PI is already defined in

I suck at c++. What are you trying to accomplish with that const struct?

Share on other sites
You can assign a static const inside the class ... what you want is this:

class Math
{
public:
static const double PI;
};

Then in your .cpp:

static const double Math::PI = 3.1415;

Now i'm not 100% on that sytax its off the top of my head, but its something pretty close to that.

 Beaten :P

Share on other sites
The correct thing to do would be to #define _USE_MATH_DEFINES before including cmath, and then use M_PI

Share on other sites
Quote:
Original post by ordered_disorder
Quote:
 Original post by daeridwell, you could try this:*** Source Snippet Removed ***Although, PI is already defined in

I suck at c++. What are you trying to accomplish with that const struct?

Something too clever for my own good, and altogether useless, really.

Share on other sites
Quote:
 Original post by snootyBut the compiler complains:only static const integral data members can be initialized within a class

I believe integral, in this sense, means integers. That means no floating-point values (ie. no floats or doubles). I could be wrong, though. Usually I initialize my variables in the constructor.

Share on other sites
<nitpick>
It should be 3.1416, or preferably something more precise. I use the value of pi from windows calculator (3.1415926535897932384626433832795)
</nitpick>

Share on other sites
Quote:
 Original post by snootyBut the compiler complains:only static const integral data members can be initialized within a class

It does what it says on the tin.

Quote:
 Original post by snootyWhy can't double be initialized?

Because the C++ ISO standard says so.

Quote:
 Original post by snootyAny solution?

All static non-integral constants must be defined outside of class defintions, just as in kaysik's example.