c++ - How can you define const static std::string in header file? -
i have class store static std::string
either const or const via getter.
i've tried couple direct approaches
1.
const static std::string foo = "bar";
2.
const extern std::string foo; //defined @ bottom of header ...//remaining code in header }; //close header class declaration std::string myclass::foo = "bar" /#endif // myclass_h
i've tried
3.
protected: static std::string foo; public: static std::string getfoo() { return foo; }
these approaches fail these reasons respectively:
- error: in-class initialization of static data member
const string myclass::foo
of non-literal type - storage class specified
foo
-- doesn't seem combiningextern
const
orstatic
- many 'undefined reference to' errors generated other parts of code , return line of getter function
the reason have declaration within header rather source file. class extended , other functions pure virtual have no other reason these variables have source file.
so how can done?
one method define method has static variable inside of it.
for example:
class yourclass { public: // other stuff... const std::string& getstring() { // initialize static variable static std::string foo("bar"); return foo; } // other stuff... };
this initialize static string once , each call function return constant reference variable. useful purpose.
Comments
Post a Comment