什么是qobject_cast?

问题描述 投票:9回答:2

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

就像,我把int作为charQString投掷使用QMessageBox意义上的类型转换,但为什么要投入不同的类?

c++ qt dynamic-cast qobject
2个回答
16
投票

在你开始学习qobject_cast之前,你需要知道C ++的dynamic_cast是什么。动态演员是关于polymorphism

C ++的动态强制转换使用RTTI(运行时类型信息)来转换对象。但qobject_cast没有RTTI这样做。

What is dynamic cast?

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

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

请注意,BmwCarAudiCar类继承Car类。使用此功能,我们可以使用一个功能制作不同的汽车。例如:

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你将无法确定carBmwCar还是AudiCar

What is different between dynamic_cast and qobject_cast?

  • qobject_cast只能用于具有QObject宏的Q_OBJECT派生类。
  • qobject_cast不使用RTTI。

15
投票

qobject_castdynamic_cast相同,但仅适用于QObject的孩子。它不需要RTTI,它的工作速度更快,因为在QObject中不可能使用multiple inheritance

不要犹豫,自我研究和阅读有关OOP和C ++的一些基本知识。特别是关于多态性。并且不要犹豫是否阅读Qt文档,它包含许多易于理解的示例。

重新使用qobject_cast正在获取指向插槽内类的指针:

QObject::connect( btn, &QPushButton::clicked, this, &MyClass::onClicked );
void MyClass::onClicked()
{
    // How to get pointer to a button:
    QObject *p = sender();
    // It's QObject. Now we need to cast it to button:
    QPushButton *btn = qobject_cast<QPushButon *>( p );
    Q_ASSERT( btn != nullptr ); // Check that a cast was successfull
    // Now we can use a QObject as a button:
    btn->setText( "We just clicked on a button!" );
}
© www.soinside.com 2019 - 2024. All rights reserved.