【发布时间】:2017-12-15 23:54:15
【问题描述】:
我有一个关于 java 的非常普遍的问题。 我想知道是否有一种简单的方法可以在 java 中重新创建这个 c++ 代码:
class A
{
public:
int first;
int second;
A(const A& other) {
*this = other;
}
...
}
所以基本上是一个复制构造函数,您可以在构造函数中将 A 的现有对象传递给 a 的新对象,它将复制内容并构建 A 的现有对象的精确副本。
尝试
class A {
int first;
int second;
public A(A other){
this = other;
}
...
}
很遗憾不起作用,因为 eclipse 告诉我“this”不允许出现在赋值的左侧,因为它不是变量。
我知道我会得到相同的结果:
class A {
int first;
int second;
public A(A other){
this.first = other.first;
this.second = other.second;
}
...
}
但我想知道是否有更简单的方法,因为有时你有更多的类变量。
提前致谢!
【问题讨论】:
-
你可以创建一个私有构造函数来接收你的所有变量,并让所有其他构造函数以某种方式调用它。
-
你的意思是一个构造函数,它接受该对象的一个实例,然后复制它的数据。这可能就这么简单。
-
@Daedric 完全正确 - 但不必单独复制其变量。 (我想知道我在提交问题后是否误用了复制构造函数这个词 - 这是否导致混淆?)
标签: java c++ constructor copy this