简体   繁体   中英

C++ Redefining variables of a namespace?

I've got two questions.

Question 1: Can someone provide an example of how to define/redefine a variable in a namespace. I've provided my own guess for you to base an your answer from.

// namespace.hpp
namespace example
{
    static string version;
    static int x;
}

And then in a .cpp how do I redefine those variables?

// namespace.cpp
namespace example
{
    version = "0.1"; // ?????
    x = 0; //???
}

Question 2: How would I attach a permanent class object onto a namespace from the same .hpp file? Something like this:

// namespace.hpp
class Idk
{
    public:
        int doThis();
}

namespace example
{
    Idk idkObject;
}

The code above, when included multiple times (from different files) will replace the object, which will cause compilation errors. Once again, I need a permanent way to attach a object to a namespace its header file.

在头文件中写入 'extern' 而不是 'static',并在 cpp 文件的变量定义中包含数据类型。

Question 1: You need to specify the type also

// namespace.cpp
namespace example
{
    string version = "0.1"; // ?????
    int x = 0; //???
}

Question 2: You shouldn't create a 'non-static' object in a header file irrespective of the namespace. You should just use static here also or else you should use extern in header file and define the variable inside a cpp file. {Note it's a little different with templatized classes}

// namespace.hpp
class Idk
{
    public:
        int doThis();
}

namespace example
{
    static Idk idkObject;
}

// namespace.cpp
namespace example
{
    Idk idkObject; // Default constructor
}

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