Reputation: 1945
I was looking up how to add static consts, the other day, to a class. I noticed that a lot of the examples were showing...
(We'll say public, for the heck of it)
test.h
class A {
public:
static const int HELLO_WORLD=1;
};
However, I wanted to define a string and this didn't compile.
test.h
class A {
public:
static const std::string HELLO_WORLD="WORLD HELLO";
};
After some research, I found out for non ints it was different. I had to declare them in the header, but set their value in the cpp file.
test.h
class A {
public:
static const std::string HELLO_WORLD;
};
test.cpp
#include "test.h"
const std::string A:HELLO_WORLD = "WORLD HELLO";
I could only find answers on how to resolve it, but not actually why it needs to be like that... MY QUESTION is why does it have to be like that, and why are ints allowed to be declared + set?
Also is there a better way to do this in c++11/c++14? (Might as well ask)
Upvotes: 2
Views: 200
Reputation: 4808
Stroustrup: "In C++98, only static const members of integral types can be initialized in-class, and the initializer has to be a constant expression. These restrictions ensure that we can do the initialization at compile-time."
Try this:
class A {
public:
constexpr static const char *HELLO_WORLD="WORLD HELLO";
};
Upvotes: 4