【发布时间】:2026-01-07 20:45:01
【问题描述】:
我不明白为什么会这样。
pReallyABase 是一个向下转换的 shared_pointer
我明白为什么编译器允许我调用 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
【问题讨论】:
-
未定义的行为意味着它所说的。
-
尝试让
onlyForDerived读取或写入Derived成员,你可能不会有这样的运气:)
标签: c++ pointers inheritance downcast