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

How to put a static class member in a namespace?

本文关键字:命名空间 成员 静态类      更新时间:2023-10-16
#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应该在全局范围内可访问,所以我希望它在命名空间下。

出路是什么?

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

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

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

您在全局命名空间中声明了类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设为静态并不是最佳做法,如果可以的话,您可能希望将其设为局部变量。

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

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

如果你想在全局范围内访问它,不要把它放在命名空间中。