命名空间中的两个对象将被不同的函数默认初始化,并由命名空间中的类使用 [英] Two objects in namespace to be default initialized by different functions and used by class within namespace

查看:249
本文介绍了命名空间中的两个对象将被不同的函数默认初始化,并由命名空间中的类使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的请求。我有一个命名空间foo,两个类型 bar 的声明对象,即 bar1 bar2 ,我想通过类的bar的构造函数初始化。这是一个很好的方法:

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();
};

这个shenanigan的原因是我想创建一个类似 cout cin ,使 foo :: bar1 foo :: bar2 不需要由用户定义。更具体地说,我使用 ncurses 并希望用输出窗口替换 cout bar1 cin 与输入窗口 bar2 c> foo :: bar1<< a在输出窗口中打印 c> a,如我认为的和 foo :: bar2>> b 从输入窗口提取值并将其转储到b中。我可以通过C函数调用这样做,但我需要帮助将其扩展到C ++。相应地, bar1 bar2 的默认初始化?

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?

推荐答案

一种方法是使用简单的函数模式。您将构造函数保持为私有,客户端只能通过两个get函数访问这些对象。您可能也想要禁用复制构造函数和复制赋值运算符。

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();
}

这篇关于命名空间中的两个对象将被不同的函数默认初始化,并由命名空间中的类使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆