在命名空间中调用函数

Calling functions within namespaces

是否可以在命名空间中调用函数?我需要这样做,因为该函数为变量分配了有意义的值。如果没有,是否有解决方法?下面是我想要的想法,foo 函数在其中为变量赋值,bar1bar2 两个变量被赋值。

namespace space{
    bar *bar1;
    bar *bar2;

    void foo(bar *b1, bar *b2) {/*b1 and b2 and given values*/}
    foo(bar1, bar2); // this foo is a function call.
}

需要说明的是,bar1 和 bar2 应该只在第一次调用时定义,其他时间不定义。

我相信这正是 OP 想要的,但这太可怕了。每个包含 space.h 的 CPP 文件都将实例化 bar 的 1 和 2 以及 init。当链接器试图解决所有问题时命名冲突地狱。

#ifndef SPACE_H
#define SPACE_H
#include <iostream>
namespace space
{
    class bar
    {
    public:
        // use your own stuff here. This is for sample use only.
        bar(const std::string & str):mStr(str)
        {

        }
        friend std::ostream &operator<<(std::ostream & out, const bar &bq)
        {
            out << bq.mStr;
            return out;
        }
    private:
        std::string mStr;
    };
    bar *bar1; // consider using std::unique_ptr in place of the raw pointer
    bar *bar2;

    class Init
    {
    public:
        Init()
        {
            bar1 = new bar("bar, bar, bar");
            bar2 = new bar("barbara anne");
        }
        virtual ~Init() // std::unique_ptr makes this destructor unnecessary
        {
             delete bar1;
             delete bar2;
        }
    }
    Init init; // init will construct and assign the bars before main 
               // and destruct and delete the bars when the program exits
}
#endif

static 稍微好一点 static 将每个栏和初始化限制为每个包含 CPP 文件的变量,但是现在您在每个包含 CPP 文件中都有重复的变量,更多的 RAM 使用和更改一个确实如此其他的不改。

    static bar *bar1;
    static bar *bar2;

    class Init
    {
    public:
        Init()
        {
            bar1 = new bar("bar, bar, bar");
            bar2 = new bar("barbara anne");
        }
        virtual ~Init()
        {
             delete bar1;
             delete bar2;
        }
    };
    static Init init;

另一个调整并不完全符合 OP 的要求,但它很接近,take 1 更安全,并且与 take 2 不同,跨编译单元统一。extern 指示编译器允许使用 bars 1和 2 没有实例化它们,但这意味着必须有人实际为它们分配 space。

    extern bar *bar1;
    extern bar *bar2;

    class Init
    {
    public:
        Init()
        {
            bar1 = new bar("bar, bar, bar");
            bar2 = new bar("barbara anne");
        }
        virtual ~Init()
        {
             delete bar1;
             delete bar2;
        }
    };

还有一个主要的 CPP 来演示使用

#include <iostream>
#include "space.h"

// allocate the bars and the Init object
space::bar *space::bar1; 
space::bar *space::bar2;

space::Init init;

int main()
{
    std::cout << *space::bar1 << std::endl;
    std::cout << *space::bar2 << std::endl;
    return 0;
}