使用基类中的派生类值

时间:2012-02-02 22:43:57

标签: c++ qt

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

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;
     }

在派生的构造函数中,我将title设置为“correct”。

当我通过创建DerivedView来运行程序时,标题仍然是“测试”。我该怎么做才能调用并获取基类的派生类值?

1 个答案:

答案 0 :(得分:2)

除非您非常牢固地掌握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")
    { }
};