Re: Something with static...
On Sep 25, 9:10 am, desktop <f...@sss.com> wrote:
Why is this struct illegal:
#include<iostream>
struct debug {
std::string d1 = "bob\n";
};
And what is it supposed to mean? There's a d1 for every
instance of the class; if you want to initialize it, you do so
in the constructor.
I get this error:
graphics/debug.h:4: error: ISO C++ forbids initialization of member ?d1?
graphics/debug.h:4: error: making ?d1? static
graphics/debug.h:4: error: invalid in-class initialization of static
data member of non-integral type ?std::string?
If I change it to:
static std::string d1 = "bob\n";
I only get:
graphics/debug.h:4: error: invalid in-class initialization of static
data member of non-integral type ?std::string?
The declaration of a static member in a class is just that; a
declaration, and not a definition. (There are technical
reasons, largely historic, for this, and I don't see it changing
any time soon.) Since it's only a declaration: 1) you need to
provide a definition somewhere, and 2) you can't initialize it.
(The initialization belongs in the definition.)
There is a special exception to this rule for static members
with a const integral type, and which is initialized with a
constant integral expression; in this case (and only in this
case), the initialization can be provided in the declaration in
the class body (but you still need to provide a definition).
I have also tried:
struct debug {
std::string d1 = getd1();
std::string getd1(){
return "bob\n";
}
};
But then I get:
graphics/debug.h:4: error: a function call cannot appear in a
constant-expression
I thought it was ok to call a function in a struct.
You can *define* a function in a class, and you can call
anything from a that function, but a class defines a data type,
and is not executable code.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34