使用基类的派生类值
Use the derived class value from the base class
试图在基类中创建一个小部件,根据我们调用的派生类,小部件中唯一会发生变化的是标题。
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")
{ }
};
相关文章:
- 如何通过派生类函数更改基类中的向量
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 在派生类中使用基类的私有成员变量的最佳方法
- 基类和派生类的多态赋值运算符
- 如何在从抽象基派生的类中实现相同的方法?
- 基类的填充将被复制到派生类中
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 指向基类派生类的 std::unique_ptr 的指针
- 为什么基类数据在派生类数据之前初始化
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 如何将基类替换为派生基类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 解析公用派生基类模板中的函数模板名称时出错"Not declared in this scope"