How do I initialize private static member
?
There is an error in the way I did it
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
class foo
{
private:
static int i;
};
int foo::i = 0;
It's because I initialized i in the header file.
static
When you write the variable,
Class declarations can be in the header file,
The static
variable must be initialized in the source file.
For example, foo.h)
class foo
{
private:
static int i;
};
foo.c/foo.cpp)
int foo::i = 0;
Like this
The reason why I have to do it like this is If you include headers from multiple source files at the same time, You have code to initialize multiple source files, so the link level gives you an error.
However, static const
can be written in the header file as follows:
However, it is only possible in the integrra
l/enum
type, so be careful
foo.h)
class foo
{
private:
static int const i = 42;
};
© 2024 OneMinuteCode. All rights reserved.