这是我的课:
class Cat {
static int lives = 9;
private String name;
private int age;
public Cat(String s, int i) {
name = s;
age = i;
}
public Cat(Cat c) {
// Failed attempt to define Copy Constructor
return new Cat(c.name,c.age);
}
public String toString() {
return (name + ", " + age);
}
}
我想定义复制构造函数,以便我可以从现有对象实例化一个新的 Cat 对象。像这样:
Cat Garfield = new Cat("Garfield",10);
Cat Tom = new Cat(Garfield);
当我尝试它时,它给出了复制构造函数定义的编译错误。请帮助我了解出了什么问题。是的,构造函数不能有返回类型,但我们在这里返回对 Cat 的引用。
最佳答案
不要做
return new Cat(c. ...
但是
this(c.name, ...)
构造函数不会通过 return 返回对象!
关于java - 在 Java 中定义复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28936124/