QT多继承出现的问题 – 使用dynamic_cast来转换

  • Post author:
  • Post category:其他


定义了一个接口,功能是用来实现添加界面控件。

1.首先看接口:

#pragma once
class IAddUserWnd {
public:
	IAddUserWnd();
	~IAddUserWnd();

	virtual void addUserWnd(void* subWnd) = 0;
};
#include "IAddUserWnd.h"

IAddUserWnd::IAddUserWnd() {
}

IAddUserWnd::~IAddUserWnd() {
}

2.定义一个Widget,然后继承这个接口,注意:要先继承QWidget然后在继承IAddUserWnd 顺序不能变,否则会出现变异错误。

#pragma once

#include <QWidget>
#include "ui_QtGuiUserWnd.h"
#include "IAddUserWnd.h"

class QtGuiUserWnd : public QWidget ,public IAddUserWnd{
	Q_OBJECT

public:
	QtGuiUserWnd(QWidget *parent = Q_NULLPTR);
	~QtGuiUserWnd();

	virtual void addUserWnd(void* subWnd)override;
private:
	Ui::QtGuiUserWnd ui;
};

#include "QtGuiUserWnd.h"
#include "IAddUserWnd.h"

QtGuiUserWnd::QtGuiUserWnd(QWidget *parent)
	: QWidget(parent) {
	ui.setupUi(this);
}

QtGuiUserWnd::~QtGuiUserWnd() {
}

void QtGuiUserWnd::addUserWnd(void* subWnd) {
	QWidget* wnd = (QWidget*)subWnd;
	ui.verticalLayout->addWidget(wnd);
}

uiw界面

在这里插入图片描述

3.调用:

	IAddUserWnd* userWnd = new QtGuiUserWnd;
	QLabel* label = new QLabel;
	label->setText(QStringLiteral("测试文本"));
	userWnd->addUserWnd(label);
	((QWidget*)userWnd)->show();

运行一下,程序出现了崩溃:

在这里插入图片描述

4.解决问题:

把调用过程中的最后一句话,

((QWidget*)userWnd)->show();

改为:

dynamic_cast<QWidget*>(userWnd)->show();

然后运行一下就成功了!aaa



版权声明:本文为wb175208原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。