什么是qobject_cast? [英] What is qobject_cast?

查看:83
本文介绍了什么是qobject_cast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以用尽可能简单的术语(或您想要的简单含义)解释什么 qobject_cast 是什么,它做什么以及为什么我们需要将一种类类型转换为另一种类类型?

Could someone explain in as simple terms as possible (or as simple as you would like) what qobject_cast is, what it does and why we would need to cast one class type to another?

就像我在将 int 转换为 char QString 的意义上进行类型转换一样,也许使用 QMessageBox ,但是为什么要转换为不同的类?

Like, I get typecasting in the sense of casting an int as a char or QString maybe to use QMessageBox, but why cast into different classes?

推荐答案

在开始学习多态的全部内容.

Before you start learning what qobject_cast is, you would need to know what C++'s dynamic_cast is. Dynamic cast is all about polymorphism.

C ++的动态转换使用 RTTI (运行时类型信息)来转换对象.但是 qobject_cast 不需要RTTI就能做到这一点.

C++'s dynamic cast uses RTTI (Run Time Type Information) to cast an object. But qobject_cast does this without RTTI.

例如,假设我们具有汽车工厂功能.像这样:

For example suppose we've got a car factory function. Like this:

Car* make_car(string brand){
    if(brand == "BMW"){
        return new BmwCar;
    }
    if(brand == "Audi"){
        return new AudiCar;
    }
    return nullptr;
}

请注意, BmwCar AudiCar 类继承了 Car 类.使用此功能,我们只能使用一个功能制造不同的汽车.例如:

Note that BmwCar and AudiCar classes inherit Car class. Using this function we can make different cars only using one function. For example:

string brand;
cin >> brand;
Car *car = make_car(brand);

BmwCar *bmw = dynamic_cast<BmwCar*>(car);
if (bmw != nullptr) {
    cout << "You've got a BMW!";
}

AudiCar *audi = dynamic_cast<AudiCar*>(car);
if (audi != nullptr) {
    cout << "You've got a Audi!";
}

没有 dynamic_cast ,您将无法确定 car BmwCar 还是 AudiCar .

Without dynamic_cast you won't be able to determine if car is a BmwCar or an AudiCar.

  • qobject_cast can only be used with QObject derived classes having Q_OBJECT macro.

qobject_cast 不使用RTTI.

这篇关于什么是qobject_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆