【问题标题】:Private constructor私有构造函数
【发布时间】:2011-04-20 22:39:33
【问题描述】:

我有一个具有私有构造函数的类对象:

class CL_GUIComponent
{
    // ...
    private:
    CL_SharedPtr<CL_GUIComponent_Impl> impl;
    CL_GUIComponent(CL_GUIComponent &other);
    CL_GUIComponent &operator =(const CL_GUIComponent &other);
    CL_GraphicContext dummy_gc;
};

我有一个类,它有一个指向我之前描述的类型的对象的指针。

class Some
{
   private:
       CL_GUIComponent *obj;
   public:
       CL_GUIComponent getComp() { return *obj; }
}

但是这段代码调用错误:

In member function ‘CL_GUIComponent Some::getComp()’:
error: ‘CL_GUIComponent::CL_GUIComponent(CL_GUIComponent&)’ is private
error: within this context

如何存储和获取该对象?

【问题讨论】:

    标签: c++ constructor private


    【解决方案1】:

    改为返回引用:

    CL_GUIComponent& getComp() { return *obj; } 
    

    和/或

    const CL_GUIComponent& getComp() const { return *obj; } 
    

    您拥有的代码正试图返回一个副本,但复制构造函数是私有的,因此它无法访问它(因此出现错误)。在任何情况下,对于非平凡的对象,几乎总是返回 const&amp; 更好(通常,并非总是如此)。

    【讨论】:

    • 这并不能解决他的问题,因为他显然无法修改该函数。
    【解决方案2】:

    通过指针或引用。你不能构造一个新的,因此不能返回副本,就像你的 get 尝试做的那样。

    【讨论】:

    • 我以为我返回的是参考,而不是副本?
    【解决方案3】:

    getComp 返回一个 CL_GUIComponent 的实例。这意味着 getComp 实际上会复制 obj 指向的实例。如果希望 getComp 返回 obj 指向的实例,则返回对 CL_GUIComponent 的引用,如下所示:

    CL_GUIComponent &getComp() {return *obj;}
    

    【讨论】:

      【解决方案4】:

      这是non-copyable 的成语。通过指针或引用返回。

      【讨论】:

        【解决方案5】:

        使用getComp() 来初始化引用。

        CL_GUIComponent const &mycomp = getComp();
        

        然后语言不会尝试在调用函数中调用复制构造函数。 (不过,getComp 仍然会创建并返回一个副本。)

        【讨论】:

          【解决方案6】:

          由于构造函数被声明为私有,您必须使用公共成员函数来创建使用私有构造函数的类的对象。

          class CL_GUIComponent 
          { 
              // ... 
              private: 
              CL_GUIComponent();
              CL_GUIComponent(CL_GUIComponent &other); 
              CL_GUIComponent &operator =(const CL_GUIComponent &other); 
              public:
              CL_GUIComponent* CreateInstance()
                   {
                     CL_GUIComponent *obj = new CL_GUIComponent();
                   }
          
          };
          class Some 
          { 
             private: 
                 CL_GUIComponent *obj; 
             public: 
                 CL_GUIComponent* getComp() { return (obj->CreateInstance()); } 
          };
          

          【讨论】:

            猜你喜欢
            • 2019-10-16
            • 1970-01-01
            • 2011-02-08
            • 2011-09-13
            • 2011-10-30
            相关资源
            最近更新 更多