简体   繁体   中英

Create a static initialise class in c++

I want to have a class that is used for a one off initialization like so:

class Initialise
{
public:
    Initialise()
    {
        m_name = "Jimmy";
    }
    ~Initialise(){}

private:
    std::string m_name;
};

class SomeClass
{
    static Initialise staticStuff; // constructor runs once, single instance
};

int main()
{
    SomeClass testl;

    return 0;
}

When I run the above I find that the constructor of the 'Initialise' class never gets hit in the debugger. Why is this?

You didn't define staticStuff , you only declared it.

You have to declare it outside of the class like so :

Initialise  SomeClass::staticStuff;

Here is a live example.


Moreover, like pointed by Borgleader, you should consider using a member initializer list to improve your code.

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