2010-11-28 18 views
4
class Parent{ 

}; 

class Child: 
    public Parent 
{ 

} 

void Func(Parent*& param) 
{ 

} 

Child* c=new Child; 

Func(c); //error 
+1

あなたはそうです。質問はなんですか? –

+0

ちょうど理由を知りたいですか? – lovespring

答えて

3

これは仕様です。

cParent*ではなく、Child*です。 Parent*に変換するには、暗黙の変換が必要です。この暗黙の変換により、少なくとも概念的にはParent*という一時オブジェクトが生成され、非const参照は一時オブジェクトにバインドできません。あなたはOKだろうと、Parent *const &を取るためにFuncを変更することができる場合

struct Parent {}; 

struct Child: Parent { int a; }; 

void Func(Parent*& param) { param = new Parent(); } 

int main() { 
    Child* c = 0; 

    Func(c); // suppose this was allowed, and passed a reference to "c". 
    c->a; // oh dear. The purpose of a type system is to prevent this. 
} 

:ここ

7

が理由です。

関連する問題