Jump to content
  • Advertisement
Sign in to follow this  
encom

javalike constants in C++

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi I'm moving from Java to C++. How to use constants in c++ classes like java : ############# JAVA class Foo { public static int A = 2; public static int B = 3; } class Bar { Bar() { println("res = " + (Foo.A + Foo.B)); // I can use it in a switch case statement } } ############ C++ class Foo (in .H) { public : static const int A; static const int B; } (in .CPP) const int Foo::A = 2; const int Foo::B = 3; class Bar { Bar() { printf("res = %d", Foo::A + Foo::B); // I can use it in a switch case statement } } It doesnt work ! 'Foo' : is not a class or namespace name Bar.cpp : error C2065: 'A' : undeclared identifier Foo.cpp : error C2051: case expression not constant Help me please :)

Share this post


Link to post
Share on other sites
Advertisement
Provided your compiler groks them you can initialize static consts in the class definition. Ex:

class Foo {
public:
static const int A = 2;
static const int B = 3;
};

Share this post


Link to post
Share on other sites
Initialisation like that :

class Foo {
public:
static const int A = 2;
static const int B = 3;
};

doesn work :

error C2258: illegal pure syntax, must be '= 0'
error C2252: 'A' : pure specifier can only be specified for functions

Share this post


Link to post
Share on other sites
if I use that :

class foo{
public:
enum{ A = 4, B = 9 };
};

In class Bar :
Error : 'Foo' : is not a class or namespace name
Error : Bar.cpp : error C2065: 'A' : undeclared identifier

Share this post


Link to post
Share on other sites
In the second case (no pun intended [smile]) you might have typed the foo in the wrong case (C++ is case sensitive). I incorrectly called the class foo when it should have been called Foo.

Share this post


Link to post
Share on other sites
Try this in a header (.hpp) file:


class Foo
{
public:
static const int A;
};


And the following in the body (.cpp) file


const int Foo::A = 4;

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!