简体   繁体   中英

C++ downcasting

This question is a followup on what I posted here

Synth implements Generator and Track has a generator member (which has a Synth in it). What I want to do is something like:

Track track = Track();
cout << track.generator.varA << endl;

But this doesn't work so I'm guessing I have to somehow cast generator to Synth first, before I can access any synthesizer methods or members and I can't figure out how to do that.

在确定您拥有的基本指针确实是该派生类型时,要将其转换为派生类型,请执行以下操作:

static_cast<Derived*>(myBasePointer)

First of all, generator is a pointer, so you cannot use the . operator to access a member of the pointed object, as you do here:

track.generator.varA // ERROR!

Secondly, since you want a pointer to a derived class and you have a pointer to a base class, you should use dynamic_cast<> to get one (unless you are sure the object pointed to is an instance of the derived class, in that case you can use static_cast<> ):

Synth* p = dynamic_cast<Synth*>(track.generator);
if (p != nullptr)
{
    cout << p->varA << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM