c++ - C++中虚方法的误解

标签 c++ qt inheritance virtual

我没有 OOP 经验。我正在使用 C++ 和 Qt 开发应用程序。我已经实现了 2 个类,一个是基础类,另一个是从它继承的类。然后我为两者添加了虚拟方法并且一切正常。但后来我意识到我不认为它应该......这是例子:

这是我的基类:

namespace Ui {
class CGenericProject;
}

class CGenericProject : public QDialog
{
    Q_OBJECT

public:
    explicit CGenericProject(QWidget *parent = 0);
    ~CGenericProject();

    EMeasures_t type();

private:
    Ui::CGenericProject *ui;

    virtual void initPlot();

protected:
    QCustomPlot* customPlot;
    QVector<double> m_x;
    QVector<double> m_y;

    EMeasures_t m_type;
};

它有一个 virtual方法称为 initPlot它看起来像这样:

void CGenericProject::initPlot()
{
    customPlot = ui->workPlot;

    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes );
    customPlot->setFocusPolicy(Qt::ClickFocus);
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->yAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(100);
    customPlot->yAxis->setTickStep(100);
    customPlot->xAxis->setRange(0, 1000);
    customPlot->yAxis->setRange(0, 1000);
}

然后我有一个派生它的类:

class CEisProject : public CGenericProject
{
public:
    CEisProject();
    ~CEisProject();

private:
    virtual void initPlot();
    void exampleEisMethod();
};

它的 initPlot在这里:

void CEisProject::initPlot()
{
    // give the axes some labels:
    customPlot->xAxis->setLabel("Re [Ohm]");
    customPlot->yAxis->setLabel("- Im [Ohm]");

    customPlot->replot();
}

这就是我创建对象的方式:

CGenericProject* test = new CEisProject();

现在,当 initPlot()方法被调用,首先是 initPlot()来自基类 CGenericProject被调用然后initPlot()来自 CEisProject叫做。我想要这个功能,我可以在通用类中预定义一些东西,然后在子类中添加特定的东西。 但是一想,不应该initPlot()是 calles exclusively?我的意思是,难道不应该从基类 子类而不是 两者 一个接一个地调用该方法吗?阅读后我注意到了这一点 this answer .

构造函数:

    CGenericProject::CGenericProject(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::CGenericProject)
    {
        ui->setupUi(this);
        initPlot();

        m_x.clear();
        m_y.clear();
    }

CEisProject::CEisProject()
{
    m_type = EMeasures_t::eEIS;
    initPlot();
}

最佳答案

您没有显示构造函数的定义,只显示了它们的声明。但我很确定构造函数定义包含您问题的答案。

您可能不知道派生类构造函数在将虚函数指向派生类之前调用了基类构造函数。因此,在基类构造(即将派生类的对象)中调用的虚函数获取该虚函数的基类定义。

关于c++ - C++中虚方法的误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367115/

相关文章:

C++通过Windows搜索路径查找可执行文件

linux - 为 arm 交叉编译 Qt 的 OpenGL 模块

Qt 设计师;难以将小部件放置在正确的父级中

c++ - 如何将派生类型视为其基类型?

c++ - 单例混合 C++

c++ - 无法在 vc++ mfc 应用程序中分配 1.5GB 内存

c++ - Qt5 中用于多媒体的后端

c++ - 使用 Boost.PropertyTree 解析 JSON 数组

c++ - 我如何在 Qt 中使用 itemFromIndex

c++ - 如何确保继承类正在实现友元函数(ostream)?