如何将静态类成员放在命名空间中?

时间:2013-02-12 07:17:07

标签: c++ namespaces static-members

#include <iostream>
#include <stdlib.h>
#include <sstream>

class api
{
private:
    void psParser ()
    {
        std::stringstream psOutput;
        psOutput << "ps --no-headers -f -p " << getpid() << " > .txt";

        system (psOutput.str().c_str());

        std::stringstream processInfo;
        processInfo << ":"__FILE__ << ":" << __DATE__ << ":" << __TIME__ << ":";
    }

public:
    static std::stringstream message;
};

namespace sstreamss
{
    std :: stringstream api :: message;
};

int main ()
{
    api::message << "zxzx";

    return 0;
}

输出:

error: definition of ‘api::message’ is not in namespace enclosing ‘api’

我希望static std::stringstream message可以在全局范围内访问,所以我想在命名空间下使用它。

出路是什么?

4 个答案:

答案 0 :(得分:1)

您在全局命名空间中声明了类api,您无法在另一个命名空间中定义成员。 您需要做的是在cpp文件中定义api::message

api.h

class api
{
private:
    void psParser ()
    {
        std::stringstream psOutput;
        psOutput << "ps --no-headers -f -p " << getpid() << " > .txt";

        system (psOutput.str().c_str());

        std::stringstream processInfo;
        processInfo << ":"__FILE__ << ":" << __DATE__ << ":" << __TIME__ << ":";
    }

public:
    static std::stringstream message;
};

api.cpp

std::stringstream api::message;

的main.cpp

#include "api.h"

int main ()
{
    api::message << "zxzx";

    return 0;
}

但是让std::stringstream静态不是最好的做法,如果可以,你可能想让它成为局部变量。

答案 1 :(得分:1)

我猜您希望所有可以访问api::message的翻译单元都可以访问相同api实例。与具有内部链接的普通非类static数据不同,static类成员具有外部链接。这意味着到处都可以看到相同的实例。因此,您不必使用命名空间来玩任何游戏。命名空间在这里不会改变任何东西,但无论如何它都必须包含整个api类。

答案 2 :(得分:1)

实现这一目标的一种方法是使用单例设计模式。定义公共静态访问器函数以访问实例。

class api
{
 private:
 static bool instanceFlag;
 static api* inst;
 ....
  ....
 public:
 static api* getInstance();
 inline void display(std::string msg)
 { 
       std::cout<<msg;
 }
};
bool api::instanceFlag = false;
api* api::inst = NULL;

api* api::getInstance()
{
 if(! instanceFlag)
 {
    inst = new api();
    instanceFlag = true;
    return inst;
 }
 else
 {
    return inst;
 }
}
int main()
{
  // Access the static instance. Same instance available everywhere
  api::getInstance()->display("zxzx");
}

答案 3 :(得分:0)

您的代码无法编译,因为您试图将api::message放入与api本身不同的命名空间中。

  

我希望static std::stringstream message可以在全球范围内访问

如果您希望在全局范围内访问它,请不要将其放在命名空间中。

相关问题