c++ - 如何将静态类成员放入命名空间中?

标签 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;
}

输出:

错误:“api::message”的定义不在包含“api”的命名空间中

我希望静态 std::stringstream 消息应该可以在全局范围内访问,所以我希望它在命名空间下。

出路在哪里?

最佳答案

实现此目的的一种方法是使用单例设计模式。定义一个公共(public)静态访问器函数来访问实例。

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");
}

关于c++ - 如何将静态类成员放入命名空间中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14827377/

相关文章:

c# - 属性 'Context' 是 F# 中的静态错误

c++ - 计算机视觉系统中机械臂的 Controller

c++ - 为什么调整图集大小后纹理无法在纹理图集中找到其位置?

c++ - 尝试通过 Eclipse-AVR 使用 Arduino 的 HardwareSerial

c++ - 通过 std::thread 传递右值

node.js - typescript 阻止导出在全局范围内可用?

python - 名称错误 : global name is not defined

c# - 命名空间隐含的上下文有多重要?

c# - 静态方法和变量在派生类中可用吗?

c++ - 如何在实例和静态范围之间创建成员变量?