2017-09-28 8 views
0

は、これらのコピーコンストラクタと動物のチャイルズ犬や猫を想像:C++リファレンス

class Animal 
{ 
    public: 
    Animal(??? other); 
} 

class Dog : Animal 
{ 
    public: 
    Dog(Dog& other); 
} 

class Cat : Animal 
{ 
    public: 
    Cat(Cat& other); 
} 

は、私は、次のコンストラクタを許可するように、親動物のクラスで???のために書くためには何がありますか:

Cat cat(otherCat); 
Dog dog(otherDog); 

ではなく、これらのそれはAnimal&になりますよう:

Cat cat(otherDog); 
Dog dog(otherCat); 
+0

スーパークラスにはコンストラクタ受け入れて動物を持っていないすることは可能でしょうか?まず、サブクラスのコンストラクタは –

+0

と呼ばれます.C++を扱っている場合、 'public'キーワードの後ろに': 'がありません。第二に、コンストラクタが継承されないので、 'otherAnimal'をそこに置くことができます – Fureeish

+0

' Dog'に 'Cat'を渡すと、あなたは何をしたいですか? – doctorlove

答えて

4

のコピーコンストラクタでは、Animal&/const Animal&と表示されます。それではCat cat(otherDog);Catのコピーコンストラクタとしてのみ動作するようにはなりません。 Dog dog(cat);のコメントを外すと、次のコードはコンパイルされません。

class Animal 
{ 
    public: 
    Animal(const Animal& other) {} 
    Animal() {} 
}; 

class Dog : Animal 
{ 
    public: 
    Dog(const Dog& other) : Animal(other) {} 
    Dog() {} 
}; 


class Cat : Animal 
{ 
    public: 
    Cat(const Cat& other) : Animal(other) {} 
    Cat() {} 
}; 

int main() 
{ 
    Cat cat; 
    Cat other(cat); 
    //Dog dog(cat); 
} 

Live Example

+0

これはコンストラクタにのみ適用されますか?私は関数speakTo(otherAnimal)を持っているので、猫は犬と猫だけ話すことができますか? – Schokocrossi

+0

@Schokocrossi Yes-ish、コンストラクタは継承されず、派生クラスに同じ名前の関数を基本クラスとして書くと、派生クラス関数は基本クラス1を非表示にします。 – NathanOliver

関連する問題