Matlab复制构造函数 [英] Matlab copy constructor
本文介绍了Matlab复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
除了用一个输入添加构造函数并显式复制其属性以外,是否有更好的方法为matlab的句柄派生类实现复制构造?
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;
等
谢谢, 丹妮
推荐答案
如果您想要一种假定可以复制所有属性的快速解决方案,请查看PROPERTIES函数.这是一个自动复制所有属性的类的示例:
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
和一些测试代码:
f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.
这篇关于Matlab复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文