使用基类的派生类值

Use the derived class value from the base class

本文关键字:派生 基类      更新时间:2023-10-16

试图在基类中创建一个小部件,根据我们调用的派生类,小部件中唯一会发生变化的是标题。

class BaseView : public QWidget {
    Q_OBJECT
public:
     explicit BaseView(QWidget *parent = 0);
protected:
     QString title; 
     virtual QString getTitle() const {
         return title;
     }

BaseView.cpp:

BaseView::BaseView(QWidget *parent) : QWidget(parent) {
     title = "test"
}
void BaseView::createTopWidget() {
    QGroupBox *topWidget = new QGroupBox(getTitle());
    ....
}

派生类标头中的:

class DerivedView : public BaseView {
    Q_OBJECT
public:
     explicit DerivedView(QWidget *parent = 0);
protected:
     QString getTitle() const {
         return title;
     }

在派生构造函数中,我将标题设置为"correct"。

当我通过创建DerivedView来运行程序时,标题仍然是"测试"。我该如何做到这一点,以便从基类中调用并获取派生类值?

除非您对C++有很强的掌握,否则您不能在构造函数中调用虚拟函数。问题是,在创建子对象的过程中,对象的类型是基子对象,而不是派生对象,因此虚拟函数调用被调度到"错误"的函数。

婴儿示例:

struct Base
{
    virtual int foo() { return 8; }
    Base() { set_something(foo()); }  // who're you gonna call?
};
struct Derived
{
    virtual int foo() { return -12; }
};
Derived d;

现在,在d.Base()的基本构造函数中,被调用的函数是d.Base::foo(),而不是d.Derived::foo()

此外,当基类构造函数运行时,成员变量title仅设置为"test",并且它尚未被派生构造函数中的赋值覆盖,派生构造函数仅在基类构造函数完成后运行

您可以通过在构造函数中明确传递标题来解决问题:

class BaseView : public QWidget
{
public:
    BaseView(QWidget * parent = 0, QString const & t = "test")
    : QWidget(parent), title(t)
    {
        something.set_title(title);
    }
    // ...
};
class DerivedView
{
public:
    DerivedView(QWidget * parent = 0)
    : BaseView(parent, "correct")
    { }
};