【问题标题】:Dpointer inheritance指针继承
【发布时间】:2013-06-13 20:00:58
【问题描述】:

我正在尝试学习如何使用来自
http://qt-project.org/wiki/Dpointer#7969fa90723037d326b77fb11381044e

的 qt 示例从 bass 类继承 d 指针

我从网站上逐字复制了它,只是稍作修改,因此代码如下所示:

小部件.h

#ifndef WIDGET_H
#define WIDGET_H

// FWD
class WidgetPrivate;
// END

class Widget {
   public:
     Widget();
   protected:
     // only sublasses may access the below
     Widget(WidgetPrivate &d); // allow subclasses to initialize with their own concrete Private
     WidgetPrivate *d_ptr;
 };

 #endif /* WIDGET_H */

widget_p.h

#ifndef WIDGET_P_H
#define WIDGET_P_H

#include <string>

#include "widget.h"

// FWD
class Widget;
// End

typedef int Rect;
typedef std::string String;

struct WidgetPrivate 
{
    WidgetPrivate(Widget *q) : q_ptr(q) { } // constructor that initializes the q-ptr
    Widget *q_ptr; // q-ptr that points to the API class
    Rect geometry;
    String stylesheet;
};

#endif /* WIDGET_P_H */

widget.cpp

#include "widget.h"

Widget::Widget()
      : d_ptr(new WidgetPrivate(this)) {
}

Widget::Widget(WidgetPrivate &d)
      : d_ptr(&d) {
}

标签.h

#ifndef LABEL_H
#define LABEL_H

#include "widget.h"

//FWD
class LabelPrivate;
//END

class Label : public Widget {
  public:
    Label();

  protected:
     Label(LabelPrivate &d); // allow Label subclasses to pass on their Private
  // notice how Label does not have a d_ptr! It just uses Widget's d_ptr.
};

#endif /* LABEL_H */

标签.cpp

#include "label.h"
#include "widget.h"
#include "widget_p.h"

 struct LabelPrivate : public WidgetPrivate 
 {        
        String text;
 };

 Label::Label()
    : Widget(*new LabelPrivate) // initialize the d-pointer with our own Private 
 {
 }

 Label::Label(LabelPrivate &d)
    : Widget(d) {
 }

当我在 g++ 中编译它时会出现这个错误

label.cpp:5:11: error: no matching function for call to ‘WidgetPrivate::WidgetPrivate()’

我在 clang 中尝试过这个,我得到或多或少相同的错误,所以问题必须在代码中,但我不知道在哪里。

【问题讨论】:

    标签: c++ class pointers inheritance


    【解决方案1】:

    LabelPrivateWidgetPrivate 公开派生,并且您没有在其成员初始化列表中为WidgetPrivate 调用适当的参数构造函数(WidgetPrivate(Widget *))。

    您要么调用适当的构造函数,要么为WidgetPrivate 提供不带参数的构造函数。

    请注意,如果您为您的类提供任何构造函数,编译器不会提供默认的无参数构造函数,因此应用的基本原理是,由于您需要定义一个构造函数,您可能需要自己定义每个构造函数。

    【讨论】:

      【解决方案2】:

      LabelPrivate 继承自 WidgetPrivate,后者没有默认构造函数,只有一个接受 Widget * 的构造函数。编译器为LabelPrivate 生成的默认构造函数将尝试默认构造其基类(WidgetPrivate),从而导致错误。你的类定义需要是这样的:

      struct LabelPrivate : public WidgetPrivate 
      {      
        LabelPrivate( Widget *w ) : WidgetPrivate( w ) {}  
        String text;
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-28
        • 1970-01-01
        • 1970-01-01
        • 2011-02-11
        • 2016-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多