【发布时间】:2009-09-04 18:46:02
【问题描述】:
有人可以解释为什么以下代码无效吗?是不是因为名为@987654323@ 的变量的偏移量与名为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 时,它会编译。
【问题讨论】:
标签: c++ pointers polymorphism reference