简体   繁体   中英

How can I forward declare an array inside a namespace in c++

I've been trying to find out how I can use namespaces properly. I want to use a namespace, but not have to define it in the header file. I am not sure how I can do this with an array inside the namespace. I either get an "already defined symbol" error, or I get told that the namespace has not been declared.

I have tried to write code like this:

//Header.h

namespace foo {
    int array[5];
}
//Source.cpp

#include "Header.h"

namespace foo {
    int array[5] = {0, 1, 2, 3, 4, 5};
}

And it returns an error.

If I try to forward-declare the namespace, like I would any other variable, it says the namespace is undefined, so I'm not sure what the correct way to achieve this is.

//Header.h

extern int foo::array;
//Source.cpp

#include "Header.h"

namespace foo {
    
    int array[5] = {0, 1, 2, 3, 4, 5};

}

This

namespace foo {

    int array[5];

}

is a definition of the array.

On the other hand, this declaration

extern int foo::array;

is present in the global namespace instead of the namespace foo . That is the namespace foo was not yet declared and you may not use the qualified name foo::array .

To declare the array in the header use the storage specifier extern .

namespace foo {

    extern int array[5];

}

And then in the cpp file you can write for example

int foo::array[5] = {0, 1, 2, 3, 4, 5};

Same way as in global namespace:

// .h
namespace foo {
    extern int array[5];
}
// .cpp
namespace foo {
    int array[5] = {1, 2, 3, 4, 5};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM