C++ 对在抽象 parent 中继承 child 的引用

C++ Reference to inhereting child in abstract parent

用这些复制构造函数想象一下动物的孩子狗和猫:

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

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

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

我必须为 parent 动物 class 中的 ??? 编写什么以允许以下构造函数:

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

但不像 Animal& 那样:

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

你只需在Animal的拷贝构造函数中取一个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