简体   繁体   中英

initialize static string member in c++

when you have a class with a static int member you can initialize it and each time you create a new instance of this class you can increment the int value.

what i want to do is that i have a static string member so i initialize it with "s" but i want to concatenate a number that would be incremented each time i create a new instance of the class.

such that for the first instance the static string value would be "s1", the second "s2" etc..

is it possible to do it with the initialize of static string member?

Just to clarify that initialization of a variable happens once only. Subsequent changes to the variable are assignments.

The requested behaviour is possible and the simplest approach would be to have an accompanying static int counter and a static const std::string prefix = "s" and assign to the static std::string as required:

#include <iostream>
#include <string>

class String_counter
{
public:
    String_counter()
    {
        value_ = prefix_ + std::to_string(++counter_);
    }
    ~String_counter()
    {
        value_ = prefix_ + std::to_string(--counter_);
    }
    static const std::string& value() { return value_; }
private:
    static int counter_;
    static const std::string prefix_;
    static std::string value_;
};

int String_counter::counter_ = 0;
const std::string String_counter::prefix_ = "s";
std::string String_counter::value_ = prefix_ + std::to_string(counter_);

int main()
{
    std::cout << String_counter::value() << std::endl;
    {
        String_counter c1;
        std::cout << String_counter::value() << std::endl;
        {
            String_counter c2;
            std::cout << String_counter::value() << std::endl;
        }
        std::cout << String_counter::value() << std::endl;
    }
    std::cout << String_counter::value() << std::endl;
    return 0;
}

Output:

$ g++ -std=c++11 main.cpp -o prog
$ ./prog 
s0
s1
s2
s1
s0

See demo @ http://ideone.com/HaFkWn .

(Note this is not thread-safe).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM