【问题标题】:Classes and inheritance qt类和继承 qt
【发布时间】:2015-10-28 11:33:02
【问题描述】:

我有 2 节课:

.cpp

MainWindow::MainWindow(QWidget *parent):
QMainWindow(parent) {
}
...
Inheritor:Inheritor(QWidget *parent):
MainWindow(parent) {
...
}

.h

class MainWindow : public QMainWindow
{
  Q_OBJECT
  QWidget *centralWidget;
public:
  MainWindow (QWidget* parent=0);
  QwtPlot *funPlot;
}
  class Inheritor : public MainWindow
{
Q_OBJECT
  QWidget *centralWidget;
public:
  Inheritor (QWidget* parent=0);
...
}

这是正确的认识吗?我有一个分段错误。我认为它就在这里。我使用在 MainWindow 类中声明的变量 funPlot。也许我的继承是错误的。你能帮帮我吗?

void Inheritor::setCheckBox() {
    first_b = new QCheckBox("option 1");
    second_b = new QCheckBox("option 2");
    third_b = new QCheckBox("option 3");
    fourth_b = new QCheckBox("option 4");
    QPushButton *drawButton = new QPushButton("Draw");
    QVBoxLayout *rightLayout = new QVBoxLayout;
    rightLayout->addWidget(first_b);
    rightLayout->addWidget(second_b);
    rightLayout->addWidget(third_b);
    rightLayout->addWidget(fourth_b);
    rightLayout->addWidget(drawButton);
    rightLayout->addStretch();
    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(funPlot);
    mainLayout->addLayout(rightLayout);
    QWidget *cent = new QWidget();
    cent->setLayout(mainLayout);
    setCentralWidget(cent);

    resize(640,480);
    connect(first_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    connect(second_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    connect(third_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    connect(fourth_b, SIGNAL(clicked()), this, SLOT(addPoints()));
    drawButton->setCheckable(true);
    connect(drawButton, SIGNAL(clicked()), this, SLOT(drawCurve()));
}

【问题讨论】:

  • Seg 错误可能是由很多原因造成的。请在一个最小的、完整的和可验证的示例中隔离问题(stackoverflow.com/help/mcve)然后发布它(包括所有 cpp 和头文件),您的帖子没有显示所有代码,无法提供帮助。
  • 这是正确的认识吗?答案是肯定的。但是你的代码肯定有问题。
  • 好的。我得到了它。谢谢
  • 我还以为是这里弄错了,因为当我评论方法的时候,一切正常,有了它,就出现了错误。
  • 如果funPlot没有被初始化并且这个函数使用它,这个函数会导致seg错误,但是问题出在MainWindow::MainWindow,因为funPlot没有被初始化。

标签: c++ qt class inheritance


【解决方案1】:

funPlot 指针未分配。

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent) 
{
    funPlot = new QwtPlot( this );
}

如果没有分配,程序很可能会在使用funPlot 时出现段错误(就像在Inheritor::setCheckBox 中使用mainLayout->addWidget(funPlot); 时一样)

【讨论】:

  • 非常感谢!它有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2015-01-18
  • 2023-03-31
  • 2020-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多