문제

Is there a way of initializing a static sub-object of a class after main() has started ?

도움이 되었습니까?

해결책

One way to do that is to replace the static member data which static member function.

Say you've this class:

class A
{
   static B static_b; //static member data
};

//.cpp
B A::static_b; //definition (required)

So instead of that you can define your class as:

class A
{
   static B static_b()  //static member function!
   {
       static B b;
       return b;
   }
};

Note that it is not thread-safe, but you can make it thread-safe as well.

다른 팁

You can use a pointer for this object:

class SomeClass{
public:
    static SomeOtherClass* p;
};

SomeOtherClass* SomeClass::p;    

void main(){
    SomeClass::p = new SomeOtherClass();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top