How to work with variable in namespace

后端 未结 3 783
猫巷女王i
猫巷女王i 2021-01-31 00:48

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

test.h:



        
3条回答
  •  情书的邮戳
    2021-01-31 00:57

    You might want to make sure your code actually has problems before you post it asking what's wrong ;)

    I copy/pasted and fixed your typos, and manually did the include:

    #include 
    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<

    result:

    $ ./a.out 
    9
    

    What you haven't said is what else is in your program. If you have more than just main.cpp, and include your test.h, then each .cpp file will have its own copy of testNum. If you want them to share then you need all but one to mark it as extern.

提交回复
热议问题