Reputation: 9064
here's the code:
#include <string>
class Config {
public:
static const std::string asdf = "hello world!";
}
I can't diagnose why this won't work
Upvotes: 2
Views: 449
Reputation: 361254
Only integral types can be initialized in the class (presuming they're declared as static const
).
So do this:
//Config.h
class Config
{
public:
static const std::string asdf; //declaration
static const int demo_integral = 100; //initialization is allowed!
}
//Config.cpp
const std::string Config::asdf = "hello world!"; //definition & initialization
const int Config::demo_integral; //already initialized in the class!
Definitions should be in .cpp
file, or else you will get multiple definition error if you define them in the header file itself and then you include the header file in multiple files!
Upvotes: 3
Reputation: 6645
From:
You are only allowed to first assign variables that are enumeration types or"integral" types -- int, char, long, etc -- inside a class definition. Char* is not an integral type, so you can only assign to it in global scope.
It is possible for you to do this as a workaround:
#include <string>
class Config {
public:
static const std::string asdf()
{
return "Hello World!";
}
};
Upvotes: 2
Reputation: 20058
You have to declare it outside of the class:
#include <string>
class Config {
public:
static const std::string asdf = "hello world!";
}
const std::string Config::asdf = "hello world";
Also look here.
Upvotes: 2
Reputation: 37427
Apart from integral types, static const members cannot be initialized within the class definition scope. You have to split it, as follows.
In header file:
#include <string>
class Config {
public:
static const std::string asdf;
};
And in .cpp file
const std::string Config::asdf = "hello world!";
Upvotes: 3
Reputation: 38143
You cannot do this.
As it is static, it must be defined outside the class ( const std::string asdf
inside your class is only declaration, because of the static
)
In your case:
const std::string Config::asdf = "hello world!"
You should initialize all data members inside constructor, not like this:
class A
{
var_t var = value;
};
Upvotes: 3