没有“等价物”,因为您不能在 Java 中重载赋值运算符。您正在尝试使用 clone() 方法来模仿该行为,但您已经把它倒退了。如果没有运算符重载,您有三种选择:
- 编写一个函数,将调用对象变为传入对象的副本。
- 编写一个函数,制作调用对象的副本并将其返回给将存储它的其他东西。
- 使用复制构造函数。
1. 编写一个函数,将调用对象变为传入对象的副本。
请注意,这与赋值运算符重载相同,只是它被命名为“copy”而不是“operator=”。
如果你想这样做:
foo A;
foo B;
A.copy(B); // A is now a copy of B.
在 C++ 中:
foo& copy(const foo& rhs)
{
if(&rhs != this)
{
this->m_someInt = rhs.m_someInt;
this->m_someBar = rhs.m_someBar;
}
return *this;
}
在 Java 中:
foo copy(foo rhs)
{
this.m_someInt = rhs.m_someInt;
this.m_someBar.copy(rhs.m_someBar);
return this;
}
请注意,在 C++ 中,按值分配this->m_someBar
给rhs.m_someBar
副本rhs.m_someBar
,但在 Java 中,这样的分配将导致两个 foo 对象共享同一个 Bar 对象。因此,如果您不打算共享子主题,也必须在子主题上使用类似的复制机制。
2. 编写一个函数,复制调用对象并将其返回给将存储它的其他东西。
如果你想这样做:
foo A;
foo B;
A = B.clone(); // A is now a copy of B.
在 C++ 中:
foo clone() const // Ignoring the fact that this is unnecessary in C++ where assignments (and returns) are by-value anyway.
{
foo theCopy;
theCopy.m_someInt = this->m_someInt;
theCopy.m_someBar = this->m_someBar;
return theCopy;
}
在 Java 中:
foo clone()
{
foo theCopy = new foo();
theCopy.m_someInt = this.m_someInt;
theCopy.m_someBar = this.m_someBar.clone();
return theCopy;
}
3. 使用复制构造函数。
如果你想这样做:
foo B;
foo A = new foo(B); // Java version
foo A(B); // C++ version
在 C++ 中:
foo(const foo& rhs)
:m_someInt(rhs.m_someInt), m_someBar(rhs.m_someBar)
{
}
// Or optionally:
foo(const foo& rhs) = default;
在 Java 中:
foo(foo rhs)
{
m_someInt = rhs.m_someInt;
m_someBar = new Bar(rhs.m_someBar);
}
总之,您的问题是您正在尝试以与上面使用 copy() 相同的方式使用 clone() 。最接近等价物的是我的copy
方法。我个人的建议是只使用一个复制构造函数并称之为一天。