简体   繁体   中英

c++ initialization of static object in class declaration

I have a C++ class (class1) with a static object of another class (class2) as a private member.

I know upon using the program I will have to initialize the static object, I can use a default constructor for this (undesired value).

Is it possible to initialize the static object to my desired value only once, and only if I create an object of the containing class (class1)?

Any help would be appreciated.

Yes.

// interface

class A {

    static B b;
};

// implementation

B A::b(arguments, to, constructor); // or B A::b = something;

However, it will be initialised even if you don't create an instance of the A class. You can't do it any other way unless you use a pointer and initialise it once in the constructor, but that's probably a bad design.

IF you really want to though, here's how:

// interface

class A {
    A() { 
        if (!Bptr)
            Bptr = new B(arguments, to, constructor);

        // ... normal code
    }

    B* Bptr;
};

// implementation

B* A::Bptr = nullptr;

However, like I said, that's most likely a bad design, and it has multithreading issues.

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