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:

  1. error: in-class initialization of static data member const string myclass::foo of non-literal type
  2. storage class specified foo -- doesn't seem combining extern const or static
  3. 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

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -