调用函数并传递带派生类型的引用指针时出错

Jar*_*red 1 c++ polymorphism pointers reference

有人可以解释为什么以下代码无效吗?是因为名为变量的偏移量d与名为b?的变量不同?

class Base { public: int foo; };

class Derived : public Base { public: int bar; };

int DoSomething( Base*& b ) { return b->foo; }

Base* b = new Derived;
Derived* d = new Derived;

int main()
{
   DoSomething( d );
}
Run Code Online (Sandbox Code Playgroud)

这是在线Comeau C++编译器给出的错误:

"ComeauTest.c", line 12: error: a reference of type "Base *&" (not const-qualified)
          cannot be initialized with a value of type "Derived *"
     DoSomething( d );
                  ^
Run Code Online (Sandbox Code Playgroud)

这是一个类似的问题,但是不同,因为在我的例子中,我声明d为指针类型:在C++中传递对指针的引用

请注意,当我传递b给它时,这会编译DoSomething.

moo*_*dow 10

想象一下,你可以做到这一点.引用不是const,因此DoSomething可以分配给指针,并且可以在调用者中看到.特别是,在DoSomething中,我们可以将指针更改为指向不是Derived实例的指针.如果调用者在我们返回后尝试对指针执行特定于派生的事情,它将会爆炸.