Matlab copy constructor

2019-03-20 13:00发布

Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties?

obj.property1 = from.property1;  
obj.property2 = from.property2;

etc.

Thanks, Dani

3条回答
冷血范
2楼-- · 2019-03-20 13:04

There is another easy way to create copies of handle objects by using matlab.mixin.Copyable. If you inherit from this class you will get a copy method which will copy all the properties for you.

classdef YourClass < matlab.mixin.Copyable
...

a = YourClass;
b = copy(a); % b is a copy of a

This copy method creates a copy without calling constructors or set functions of properties. So this should be faster. You can also customize the copy behavior by overriding some methods.

查看更多
欢心
3楼-- · 2019-03-20 13:08

You can even use

try
 F.(fns{i}) = rhs.(fns{i});
end

which makes the method more useful

查看更多
对你真心纯属浪费
4楼-- · 2019-03-20 13:17

If you want a quick-and-dirty solution that assumes all properties can be copied, take a look at the PROPERTIES function. Here's an example of a class that automatically copies all properties:

classdef Foo < handle
  properties
    a = 1;
  end
  methods
    function F=Foo(rhs)
      if nargin==0
        % default constructor
        F.a = rand(1);
      else
        % copy constructor
        fns = properties(rhs);
        for i=1:length(fns)
          F.(fns{i}) = rhs.(fns{i});
        end
      end
    end
  end
end

and some test code:

f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.
查看更多
登录 后发表回答