Inheritance 超类可以返回子类吗?例如,对于Marry函数?

Inheritance 超类可以返回子类吗?例如,对于Marry函数?,inheritance,polymorphism,covariance,Inheritance,Polymorphism,Covariance,假设我有一个方法,我希望它的返回类型与类相同。e、 猫:玛丽(猫y)或狗:玛丽(狗y)但是我不想猫和狗结婚 有没有一种编程语言可以让我表达这一点,如果你想娶一只猫和一只狗,它会给出一个编译时错误?e、 g class Animal{ void Marry(Animal X){ Console.Write(this+" has married "+X); } } class Cat:Animal{} class Dog:Animal{} 因此,我希望允许(新猫()).m

假设我有一个方法,我希望它的返回类型与类相同。e、 猫:玛丽(猫y)或狗:玛丽(狗y)但是我不想猫和狗结婚

有没有一种编程语言可以让我表达这一点,如果你想娶一只猫和一只狗,它会给出一个编译时错误?e、 g

class Animal{
    void Marry(Animal X){
      Console.Write(this+" has married "+X);
   }
}
class Cat:Animal{}
class Dog:Animal{}
因此,我希望允许
(新猫()).mary(新猫())
,但不允许
(新猫()).mary(新狗())

换句话说,我希望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> { ... }
类动物{
无效婚姻(T其他){
...
}
}
类Cat扩展了动物{…}
类狗扩展动物{…}
下面是我在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> {

}
公共类测试{
公共静态void main(字符串[]args){
最终狗=新狗();
最终Cat=新Cat();
猫。玛丽(猫);
结婚(狗);
}
}
类动物{
无效婚姻(T其他){
}
}
狗类动物{
}
猫科动物{
}

> p>你可以在C++中使用:

模板
类动物{
无效婚姻(派生X)
{
//代码在这里
}
}
狗类:动物
{
}
类别猫:动物
{
}

我相信C#中的想法是一样的,只是语法略有不同:class Animal where T:Animal返回一个类型的T可以吗?你必须将Animal强制转换为T吗?是的,你可以有一个方法返回类型T,不需要强制转换。我在sharp中尝试了这个方法,但没有成功:公共类Animal{T foo(){return(T)this;}}}公共类Cat:Animal{}你需要准确地发布你尝试过的内容,让我知道出了什么问题。我制作了一个版本,它的编译和行为完全符合预期。我将编辑我的帖子并将代码粘贴到其中,以便您可以看到。
template <typename Derived>
class Animal{
    void Marry(Derived X)
    {
       //code here  
    }
}

class Dog : Animal<Dog>
{
}

class Cat : Animal<Cat>
{
}