super class return subclass 可以吗?例如 Marry 函数?

Can a super class return a subclass? For example for a Marry function?

假设我有一个方法,我希望 return 类型与 class 相同。例如Cat:Marry(Cat y)Dog:Marry(Dog y)但我不想猫嫁狗!

是否有一种编程语言可以让我表达这一点并在您尝试嫁给猫狗时给出编译时错误?例如

class Animal{
    void Marry(Animal X){
      Console.Write(this+" has married "+X);
   }
}
class Cat:Animal{}
class Dog:Animal{}

因此我希望 (new Cat()).Marry(new Cat()) 被允许而不是 (new Cat()).Marry(new Dog())

换句话说,我希望 Marry 的参数类型与其 class 匹配。任何语言都这样做吗? (不必编写多个 Marry 函数?)我正在设想这样的事情:

void Marry(caller X){
    Console.Write(this+" has married "+X);
}

您可以在 Java 中使用泛型执行此操作:

class Animal<T extends Animal> {
  void marry(T other) {
    ...
  }
}

class Cat extends Animal<Cat> { ... }
class Dog extends Animal<Dog> { ... }

这是我在 Java 8 中正常工作的一段代码,对于那些想要更具体答案的人:

public class Test {
    public static void main(String[] args) {
        final Dog dog = new Dog();
        final Cat cat = new Cat();
        cat.marry(cat);
        dog.marry(dog);
    }
}

class Animal <T extends Animal> {
    void marry(T other) {

    }
}

class Dog extends Animal<Dog> {

}

class Cat extends Animal<Cat> {

}

您可能可以使用 CRTP:

在 C++ 中实现此目的
template <typename Derived>
class Animal{
    void Marry(Derived X)
    {
       //code here  
    }
}

class Dog : Animal<Dog>
{
}

class Cat : Animal<Cat>
{
}