gpt4 book ai didi

c++ - static_pointer_cast pReallyABase = static_pointer_cast(pBase) 有效!为什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:12 27 4
gpt4 key购买 nike

<分区>

我不明白为什么会这样。pReallyABase 是一个向下转换的 shared_pointer< Derived >,它指向一个基类实例。

我理解为什么编译器让我调用 pReallyABase->onlyForDerived() 因为我将它定义为派生类指针,但是当我尝试使用该指针调用派生类函数时为什么没有出现运行时错误?

class Base { 
public:
virtual string whatAmI() {
return "I am a Base";
}
};

class Derived : public Base {
public:
virtual string whatAmI() {
return "I am a Derived";
}

string onlyForDerived() {
return "I can do Derived things";
}
};


int main(int argc, char *argv[]) {
shared_ptr<Base> pBase = shared_ptr<Base>(new Base);
shared_ptr<Derived> pReallyABase = static_pointer_cast<Derived>(pBase);

cout << pReallyABase->whatAmI() << endl;
cout << pReallyABase->onlyForDerived() << endl; //Why does this work?
return 0;
}

结果

I am a Base
I can do Derived things

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com