How to initialize const / non-const element?

class Foo { private: int m_i; public: Foo(int i) : m_i(i) {} }; class FooA { private: const static Foo & m_foo; static Foo & m_foo2; }; 

Q1> how to initialize a constant static link?

Q2> How to initialize a non-static static link?

Note: You can make changes to the FooA class to illustrate the methods.

+4
source share
3 answers

In the same way, you initialize the non-reference static members:

 //Foo.cpp const Foo & FooA::m_foo = fooObj1; Foo & FooA::m_foo2 = fooObj2; 

where fooObj1 and fooObj2 are global variables of type Foo .

Note fooObj1 and fooObj2 must be initialized to m_foo and m_foo2 , otherwise you may run into the problem of static initialization of the fiasco order .

+10
source

Like any other static data item:

 Foo foo(5); const Foo& FooA::m_foo(foo); Foo& FooA::m_foo2(foo); 
+5
source

You initialize constant and constant static links in the same way as you initialize any static member: by initializing in the global scope.

 const Foo& FooA::m_foo = ...whatever... Foo& FooA::m_foo2 = ...whatever... 
+3
source

All Articles