Ita*_*ham 5 c++ inheritance pointers casting
如果我没有为Base**指定显式强制转换,为什么会出现编译错误?
处理派生类时,我可以使用指针指针吗?
class Base { };
class Child : public Base { };
void SomeFunction(Base** ppoObj) {}
void SomeFunction(Base* poObj) {}
int main()
{
Child *c = new Child();
// This passed.
SomeFunction(c);
SomeFunction((Base**)&c);
// CompilationError
SomeFunction(&c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
虽然你可以隐式地转换Child*为Base*,但是没有隐式Child**转换Base**,因为它可能被用来违反类型安全性.考虑:
class Base { };
class Child1 : public Base { };
class Child2 : public Base { };
int main() {
Child1 *c = new Child1();
Base **cp = &c; // If this were allowed...
*cp = new Child2(); // ...then this could happen. (*cp is a Base*)
}
Run Code Online (Sandbox Code Playgroud)