L
Lighter
See an example at first:
hdr.h
--------------
struct X
{
static const int m = 9;
};
=====================
source1.cpp
---------------
#include "hdr.h"
const int X::m;
=====================
main.cpp
---------------
#include "hdr.h"
int main()
{}
=====================
link error:
source1.obj : error LNK2005: "public: static int const X::m" (?
m@X@@2HB) already defined in main.obj
According to the C++ standard 9.4.2/4
"If a static data member is of const integral or const enumeration
type, its
declaration in the class definition can specify a constant-initializer
which
shall be an integral constant expression. In that case, the member
can
appear in integral constant expressions within its scope. The member
shall
still be defined in a namespace scope if it is used in the program and
the
namespace scope definition shall not contain an initializer."
Judging from the rule above, my code is correct. However, if I
commented the statement: const int X::m; then everything is ok. Why?
hdr.h
--------------
struct X
{
static const int m = 9;
};
=====================
source1.cpp
---------------
#include "hdr.h"
const int X::m;
=====================
main.cpp
---------------
#include "hdr.h"
int main()
{}
=====================
link error:
source1.obj : error LNK2005: "public: static int const X::m" (?
m@X@@2HB) already defined in main.obj
According to the C++ standard 9.4.2/4
"If a static data member is of const integral or const enumeration
type, its
declaration in the class definition can specify a constant-initializer
which
shall be an integral constant expression. In that case, the member
can
appear in integral constant expressions within its scope. The member
shall
still be defined in a namespace scope if it is used in the program and
the
namespace scope definition shall not contain an initializer."
Judging from the rule above, my code is correct. However, if I
commented the statement: const int X::m; then everything is ok. Why?