Two objects in namespace to be default initialized

2019-08-29 05:30发布

问题:

I have a strange request. I have a namespace foo with two declared objects of type bar, namely bar1 and bar2, which I would like to initialize via constructor of class bar. Is this a sound way to do so:

namespace foo {
    class bar;
    foo::bar *bar1;
    foo::bar *bar2;
}

class foo::bar
{
    /* Initialize bar1 and bar2 in the constructor.
     */
    InitializeBar();
};

The reason behind this shenanigan is I would like to create an object similar to cout and cin such that foo::bar1 and foo::bar2 need not be defined by the user. More specifically, I am using ncurses and wish to replace cout with an output window bar1 and cin with an input window bar2 and overload the operators and such that foo::bar1 << a prints a in the output window as I see fit and foo::bar2 >> b extracts the values from the input window and dumps it into b. I am able to do this via the C functions call but I need help to extend it to C++. Perhaps default initialization of bar1 and bar2 accordingly?

回答1:

One way is to use the simple function pattern. You keep the constructor as private and the clients can only access these objects via two get functions. You probably want to disable the copy constructor and copy assignment operator as well.

// .h
namespace foo
{
   class bar: boost noncopyable
   {
   public:
      static bar* getInputWindow()
      {
         static bar s_input;
         return &s_input;
      }
      static bar* getOutputWindow()
      {
         static bar s_output;
         return &s_output;
      }

   private:
      bar()
      {
      }
   };

   // global/namespace objects clients should directly use
   extern bar *input;
   extern bar *output;
}

// .cpp
namespace foo
{
   bar *input = bar::getInputWindow();
   bar *output = bar::getOutputWindow();
}