Let me improve the code in one step. I will explain what I do at every step.
Step 1, this is not Java. You do not need to specify a publication for each member. Everything after public: is publicly available until you specify something else ( protected or private ). I also moved the definition of pFoo after the class. You cannot define a variable before declaring it.
class CFoo { public: static CFoo *pFoo[2]; CFoo(int a); CFoo *getFoo(); }; CFoo* CFoo::pFoo[2] = {0};
Step 2, pFoo probably should not be public if you have a getFoo member function. Allow you to force an interface to a class, rather than exposing internal data.
class CFoo { public: CFoo(int a); CFoo *getFoo(); private: static CFoo *pFoo[2]; }; CFoo* CFoo::pFoo[2] = {0};
Step 3, you can return with a pointer without bothering to use new . I have written C ++ code for many years, and I will need to see how you delete memory that was entered for the static member variable. It's not worth the hassle to figure it out, so let's just pop them on the stack. Also, return them with a const pointer so that users do not accidentally modify two static CFoo objects.
class CFoo { public: CFoo(int a); const CFoo *getFoo(); private: static CFoo foos[2]; }; CFoo CFoo::foos[2] = {CFoo(0), CFoo(1)};
The getFoo implementation then becomes:
const CFoo * CFoo::getFoo() { return &foos[0];
IIRC, the static member foos will be highlighted the first time you create a CFoo object. So this code ...
CFoo bar; const CFoo *baz = bar.getFoo();
... is safe. A pointer named baz will point to the static member foos[0] .
source share