如何将静态类成员放在命名空间中
How to put a static class member in a namespace?
#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
应该可以在全球范围内访问
如果你想在全局范围内访问它,不要把它放在命名空间中。
相关文章:
- 命名空间 std 没有成员any_of
- 为什么 Clang 在命名空间'std'中没有名为 'copy' 的成员给出错误
- 初始化命名空间中的变量是否类似于将它们初始化为类成员?
- 在 c++ 中使用类的命名空间定义类的成员
- Catalina C++:使用<cmath>标头产生错误:全局命名空间中没有名为 'signbit' 的成员
- 命名空间 Win 没有成员"simpleControl"是什么意思
- Visual Studio 2017:命名空间"System"没有成员"Windows"
- 如何从嵌套在命名空间中的类调用成员函数?
- 成员的结构与命名空间的潜在范围
- 类成员函数在其命名空间之外定义
- Typedef 不是命名空间的成员
- 无法解析命名空间成员"线程"
- C++中的命名空间成员(使用与不使用)
- 使用不同文件中的命名空间成员
- 非限定名称查找查找内联命名空间成员
- 用户声明的命名空间成员
- ISO c++草案(n3290)中的一点:3.4.3.2/1命名空间成员
- 试图通过using-declaration定义命名空间成员
- Linux CLion 无法解析命名空间成员
- C++命名空间成员在不同文件中的访问如何?"namespace std"如何实施?