Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

c++ - How can you define const static std::string in header file?

I have a class that I would like to store a static std::string that is either truly const or effectively const via a getter.

I've tried a couple direct approaches
1.

const static std::string foo = "bar";

2.

const extern std::string foo; //defined at the bottom of the header like so 
...//remaining code in header
};  //close header class declaration
std::string MyClass::foo = "bar"
/#endif // MYCLASS_H

I've also tried

3.

protected:
    static std::string foo;
public:
    static std::string getFoo() { return foo; }

These approaches fail for these reasons respectively:

  1. error: in-class initialization of static data member const string MyClass::foo of non-literal type
  2. storage class specified for foo -- it doesn't seem to like combining extern with const or static
  3. many 'undefined reference to' errors generated by other parts of my code and even the return line of the getter function

The reason I would like to have the declaration within the header rather than source file. This is a class that will be extended and all its other functions are pure virtual so I currently have no other reason than these variables to have a source file.

So how can this be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One method would be to define a method that has a static variable inside of it.

For example:

class YourClass
{
public:

    // Other stuff...

    const std::string& GetString()
    {
        // Initialize the static variable
        static std::string foo("bar");
        return foo;
    }

    // Other stuff...
};

This would only initialize the static string once and each call to the function will return a constant reference to the variable. Useful for your purpose.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...