javalike constants in C++

Started by
17 comments, last by anonuser 18 years, 9 months ago
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 :)
Advertisement
class foo{public:enum{ A = 4, B = 9 };};

But this only works for integral types.
You need to #include the header. #include "foo.h" in your C++ file.
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;};
Thanks :)
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
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

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.
Whooops :D

You'r right lol, i'm a little bit inattentive.
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;

This topic is closed to new replies.

Advertisement