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

时间:2010-11-28 08:02:43

标签: c++

class Parent{

};

class Child:
   public Parent
{

}

void Func(Parent*& param)
{

}

Child* c=new Child;

Func(c); //error

3 个答案:

答案 0 :(得分:7)

原因如下:

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 &,那就没问题。

答案 1 :(得分:4)

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

请注意,这与转换Derived *&到Base *&。

干杯&第h。,

答案 2 :(得分:3)

这是设计的。

c不是Parent*,而是Child*。要将其转换为Parent*,需要进行隐式转换。此隐式转换生成临时Parent*对象(至少在概念上),并且非const引用不能绑定到临时对象。