How to initialize private static members

Asked 2 years ago, Updated 2 years ago, 111 views

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;

c++ initialization static static-members

2022-09-22 14:13

1 Answers

It's because I initialized i in the header file. staticWhen 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 integrral/enum type, so be careful

foo.h)

class foo
{
private:
    static int const i = 42;
};


2022-09-22 14:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.