4 回答
You declared class api
in global namespace you can't define member in another namespace.
What you need to do is to define api::message
in a cpp file
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;
}
But it's not the best practice to make std::stringstream
static, you may want to make it a local variable if you could.
I am guessing that you want to have the same instance of api::message
accessible across all translation units that have access to api
. Unlike plain, non-class static
data, which have internal linkage, static
class members have external linkage. This means the same instance is seen everywhere. So you do not have to play any games with namespaces. A namespace wouldn't change anything here, but it would have to enclose the whole api
class anyway.
One way to achieve this is to use singleton design pattern. Define a public static accessor function to access the instance.
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");
}
Your code doesn't compile because you're trying to put api::message
into a different namespace from api
itself.
I want that
static std::stringstream message
should be accessible at a global scope
If you want it accessible at the global scope, don't put it in a namespace.