javalike constants in C++
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 :)
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;};
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
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
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.
Try this in a header (.hpp) file:
And the following in the body (.cpp) 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
Popular Topics
Advertisement