What is qobject_cast?

前端 未结 2 1186
既然无缘
既然无缘 2020-12-29 06:13

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

2条回答
  •  攒了一身酷
    2020-12-29 06:31

    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++'s dynamic cast uses RTTI (Run Time Type Information) to cast an object. But qobject_cast does this without RTTI.

    What is dynamic cast?

    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;
    }
    

    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(car);
    if (bmw != nullptr) {
        cout << "You've got a BMW!";
    }
    
    AudiCar *audi = dynamic_cast(car);
    if (audi != nullptr) {
        cout << "You've got a Audi!";
    }
    

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

    What is different between dynamic_cast and qobject_cast?

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

    • qobject_cast doesn't use RTTI.

提交回复
热议问题