有人可以解释为什么下面的代码无效吗?是否因为名为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);
}
这是错误the online Comeau C++ compiler给出:
"ComeauTest.c", line 12: error: a reference of type "Base *&" (not const-qualified)
cannot be initialized with a value of type "Derived *"
DoSomething(d);
^
这是一个类似的问题,但不同的是,因为在我的例子,我声明d
为指针类型:Passing references to pointers in C++
注当我通过b
到DoSomething
时,这确实会编译。