复制构造函数类实例化
这是我的类,它实现了复制构造函数,
public class TestCopyConst
{
public int i=0;
public TestCopyConst(TestCopyConst tcc)
{
this.i=tcc.i;
}
}
我尝试在我的主方法中为上述类创建一个实例,
TestCopyConst testCopyConst = new TestCopyConst(?);
我不确定应该传递什么作为参数。如果我必须传递 TestCopyConst 的实例,那么我必须再次选择“new”,这又会再次提示输入参数,
TestCopyConst testCopyConst = new TestCopyConst(new TestCopyConst(?));
这里缺少什么?或者复制构造函数的概念本身是不同的?
Here is my class that implements copy constructor
public class TestCopyConst
{
public int i=0;
public TestCopyConst(TestCopyConst tcc)
{
this.i=tcc.i;
}
}
i tried to create a instance for the above class in my main method
TestCopyConst testCopyConst = new TestCopyConst(?);
I am not sure what i should pass as parameter. If i have to pass a instance of TestCopyConst then again i have to go for "new" which in turn will again prompt for parameter
TestCopyConst testCopyConst = new TestCopyConst(new TestCopyConst(?));
what is missing here? or the concept of copy constructor is itself something different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您缺少一个不是复制构造函数的构造函数。复制构造函数复制现有对象,您首先需要另一种方法来创建它们。只需创建另一个具有不同参数和不同实现的构造函数即可。
You're missing a constructor that isn't a copy constructor. The copy constructor copies existing objects, you need another way to make them in the first place. Just create another constructor with different parameters and a different implementation.
您还需要实现一个无参数构造函数:
或者一个采用
i
的构造函数:然后,您可以简单地执行以下操作:
或者这样:
通常,您的类将有一个默认的无参数构造函数;当您实现自己的构造函数时,情况就不再是这样了(假设这是 Java,它看起来像这样)。
You need to also implement a no-arg constructor:
Or one that takes an
i
:Then, you can simply do this:
Or this:
Normally, your class will have a default no-arg constructor; this ceases to be the case when you implement a constructor of your own (assuming this is Java, which it looks like).
您可以使用复制构造函数作为重载构造函数来克隆对象,但您还需要另一个构造函数以正常方式初始化实例:
You would use a Copy Constructor as an overloaded constructor to clone an object, but you also need another constructor to initialize an instance in a normal way:
Java 不像 C++ 那样具有复制构造函数,即由编译器自动生成和/或调用。您可以自己定义一个,但只有您调用它时它才有用。完全不是一回事。
在这里,您证明了这一点。您可以传递给复制构造函数的唯一内容是同一类(或派生类...)的另一个实例。如果您没有另一个实例可供复制,那么为什么您认为您根本需要复制构造函数?
Java doesn't have copy constructors in the way C++ has them, i.e. that are automatically generated and/or called by the compiler. You can define one yourself but it only has a use if you call it. Not the same thing, by a long chalk.
Here you are proving the point. The only thing you can pass to a copy constructor is another instance of the same class (or derived class...). If you don't have another instance to copy, why do you think you need a copy constructor at all?
你需要
You need