How to work with a variable in a namespace

I think I have a fundamental misunderstanding of the namespace and / or static variable. But I tried this test code (typed manually, forgive typos)

test.h:

namespace test{
   static int testNum=5;
   void setNum(int value);
}

main.cpp:

#include <test.h>

int test::setNum(int value){
   testNum=value;
}

int main(){
    test::setNum(9);
    cout<<test::testNum;
}

when I run this, I get a value of 5, not 9, as I expected. It seems almost as if I had two instances of the testNum variable, but this seems to be the exact opposite of what static should do. I suppose I made a mistake in assuming that these functions were identical to their equivalent java equvilants ...

I also get an error message indicating that testNum is declared multiple times if I remove the statics from my testNum declaration, can anyone explain why this is so?

thank

+5
3

-, , static. testNum, , .

, , , test.cpp, test.h setNum.

(.. ) ​​ static, , . " ", ( ). , static int testNum, , testNum (, static int testNum, static double testnum static char* testNum .) , , , testNum.

, static testNum , test.h. , testNum , testNum, , .

- non-const static .

static testNum , test.h, : . - , , , , extern:

extern int testNum;  // N.B. no "= 1" here

, " ", testNum, , testNum, ( - linakge, .) extern , , (.. , ) :

int testNum = 1;
+15

static , . , , static, ; , , . . ( , , .)

static . .

: extern, static. ​​extern , . , - ( ). - :

extern int testNum = 5;
int testNum = 5;
int testNum;          //  implicitly initialized with 0.

EDIT:

: :

  • (, , mdash )
  • ; , .

static . ( static, ++; .)

. , :

  • , , , ,
  • , , , static
  • , , , , static. .

, main, , main.

:

  • , , , static, ( static ), ​​ const extern,
  • , , , static
  • , , .

, , . , ( ) . , , - (), . , extern .

+4

, , , , ;)

/ , :

#include <iostream>
using namespace std;

namespace test{
   static int testNum=5;
   void setNum(int value);
}

void test::setNum(int value){
   testNum=value;
}

int main(){
    test::setNum(9);
    cout<<test::testNum;
}

:

$ ./a.out 
9

, , , . , main.cpp, test.h, .cpp testNum. , , , , extern.

+1
source

All Articles