How to initialize private static members in C++?

后端 未结 17 2554
忘掉有多难
忘掉有多难 2020-11-21 07:04

What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:

class foo
{
           


        
17条回答
  •  失恋的感觉
    2020-11-21 07:26

    int foo::i = 0; 
    

    Is the correct syntax for initializing the variable, but it must go in the source file (.cpp) rather than in the header.

    Because it is a static variable the compiler needs to create only one copy of it. You have to have a line "int foo:i" some where in your code to tell the compiler where to put it otherwise you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.

提交回复
热议问题