c++ - 强制转换为派生类的 ptr 到 ptr

标签 c++ pointers inheritance 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;
}

最佳答案

尽管您可以将 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*)
}

More information in the C++ FAQ

关于c++ - 强制转换为派生类的 ptr 到 ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38998357/

相关文章:

c++ - Direct3D Sprite->SetTransform 用法?

c++ - 如何使用 CMake 从版本控制中可移植地获取仅 header 库?

c - 指向结构的指针不递增

python - 从类中的一个方法继承的两个方法在实例上是不同的,不是吗?

使用成员函数作为模板参数时的c++编译错误

c++ - 如何捕获范围错误的 out_of_range 异常( vector 差一错误)

C: printf ("%s\n", str) 产生乱码?

c - 使用不分配的二维指针

C#字段的继承

java - 如何让子类使用父类的 protected 方法?