什么是qobject_cast? [英] What is 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?
推荐答案
在开始学习 dynamic_cast
是.动态转换是关于多态的全部内容.
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
仅可用于Q_OBJECT 的> QObject
qobject_cast
can only be used withQObject
derived classes havingQ_OBJECT
macro.
qobject_cast
不使用RTTI.
这篇关于什么是qobject_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!