代码之家  ›  专栏  ›  技术社区  ›  lovespring

当函数需要引用父指针时,无法将子类指针传递给函数,为什么?

c++
  •  4
  • lovespring  · 技术社区  · 15 年前
    class Parent{
    
    };
    
    class Child:
       public Parent
    {
    
    }
    
    void Func(Parent*& param)
    {
    
    }
    
    Child* c=new Child;
    
    Func(c); //error
    
    3 回复  |  直到 15 年前
        1
  •  3
  •   James McNellis    15 年前

    这是故意的。

    c 不是 Parent* ,它是一个 Child* . 把它变成 母公司* ,需要隐式转换。此隐式转换生成临时 母公司* 对象(至少在概念上)和非常量引用不能绑定到临时对象。

        2
  •  7
  •   Steve Jessop    15 年前

    原因如下:

    struct Parent {};
    
    struct Child: Parent { int a; };
    
    void Func(Parent*& param) { param = new Parent(); }
    
    int main() {
        Child* c = 0;
    
        Func(c); // suppose this was allowed, and passed a reference to "c".
        c->a;    // oh dear. The purpose of a type system is to prevent this.
    }
    

    如果你能改变 Func 采取 Parent *const & ,那就好了。

        3
  •  4
  •   Cheers and hth. - Alf    15 年前

    参见C++FAQ项 "21.2 Converting Derived* → Base* works OK; why doesn't Derived** → Base** work?" .

    请注意,这与将派生的*&转换为基的*&是同一个问题;。

    干杯。,