次のコードが有効でない理由を説明できますか?変数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
に渡すとコンパイルされます。