有人可以解釋爲什麼下面的代碼無效嗎?是否因爲名爲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
時,這確實會編譯。