刚刚开始在 Matlab OO 编程中进行崩溃处理,我想为一个对象编写一个 set 方法,该方法将设置该值,然后通过在另一个对象的相关字段中设置自身来回报。
classdef Person
properties
age;
sex;
priority; % net priority based on all adjustment values
adjustment; % personal adjustment value for each interest
family;
end
methods
function obj = set.sex(obj, value)
if value == 'm' || value == 'f'
obj.sex = value;
else
error('Sex must be m or f')
end
end
function obj = set.family(obj,value)
if class(value) == 'Family'
obj.family = value;
else
error('Family must be of type Family')
end
end
end
end
classdef Family
properties
husband;
wife;
children;
elders;
adjustment; % interest adjustment values
end
methods
function this = set.husband(this,person)
if class(person) == 'Person'
this.husband = person;
person.family = this;
else
error('Husband must be of type Person')
end
end
function this = set.wife(this,person)
if class(person) == 'Person'
this.wife = person;
person.family = this;
else
error('Wife must be of type Person')
end
end
end
end
所以我现在要做的是:
p = Person
f = Family
f.husband = p
p.family = f
我想要的是让家人和人自动设置自己:
p = Person
f = Family
f.husband = p
并且 Family set.husband 函数将 p 的家庭值设置为 f。为什么我的代码不起作用?据我所知,我正在做评论中建议的事情。
编辑:经过一番折腾,我已经确认“this”和“person”是正确类型的对象。最终的问题是 Matlab 通过值而不是通过引用传递。除非有人知道解决办法,否则我会尽可能回答自己。