Java相当于C++拷贝赋值运算符

p.d*_*llo 7 c++ java operator-keyword

我试图理解用C++编写的这个操作符函数并将其转换为Java.

Class& Class::operator=(const Class& In) {

   properties = In.properties;

   return *this;

}
Run Code Online (Sandbox Code Playgroud)

这只是复制类对象的实例和属性吗?我已经写了一些东西:

public static Class copy(Class obj) {
    //returns new instance of Class individual
    Class copy =  new Class(obj.row_num, obj.col_num, obj.input_length, obj.output_length, obj.max_arity, obj.function_length, obj.levels_back);
    copy.genes = obj.genes.clone();
    return copy;
}
Run Code Online (Sandbox Code Playgroud)

我在正确的轨道上吗?非常感谢您的帮助.

das*_*ght 3

& 符号&在 C++ 中指定引用。需要提供类似于 Java 对象“开箱即用”提供的行为,因为 Java 通过引用来管理对象。

当传递引用时,C++ 中不会进行复制。const事实上,避免复制是使用引用作为函数参数的主要原因。

您显示的代码也不执行复制:它根据“分配”的值更改其状态。在 Java 中对此进行建模的最接近的方法是提供一种assign(Class other)方法来更改当前状态以匹配传入对象的状态:

Class assign(Class other) {
    this.properties = other.properties;
    return this;
}
Run Code Online (Sandbox Code Playgroud)

您需要使用此方法代替 C++ 的赋值,如下所示:

Class clOne(args1);
Class clTwo(args2);
clOne = clTwo;      // Using the assignment operator
Run Code Online (Sandbox Code Playgroud)

变成这样:

Class clOne = new Class(args1);
Class clTwo = new Class(args2);
clOne.assign(clTwo); // Using the assignment method instead of the operator
Run Code Online (Sandbox Code Playgroud)