对象方法中的自引用 [英] Self reference within an object method
问题描述
刚开始在Matlab OO编程中进行崩溃检查,我想为一个对象编写一个set方法,该方法将先设置值,然后通过在另一个对象的相关字段中进行设置来进行往复操作.
Just started crash coursing in Matlab OO programing and I would like to write a set method for a object that will set the value then reciprocate by setting itself in the relevant field on the other object.
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
我想要的是家人和个人彼此自动设置:
What I would like is for family and person to auto set themselves in each other:
p = Person
f = Family
f.husband = p
Family set.husband函数会将p的family值设置为f.为什么我的代码不起作用?据我所知,我正在做评论中建议的事情.
And Family set.husband function will set p's family value to f. Why is my code not working? As far as I can tell I'm doing what is suggested in the comments.
经过一番混乱之后,我确认"this"和"person"是正确类型的对象.最终,问题在于Matlab通过值而不是通过引用传递.除非有人知道可以解决的办法,否则我会在可能的时候回答自己.
After some messing around I've confirmed that "this" and "person" are objects of the correct type. Ultimately the issue is that Matlab passes by value rather then by reference. Unless anyone knows a way around that I'll answer myself when I can.
推荐答案
通常将普通对象视为value
对象.将它们传递给函数或方法时,仅传递值,而不传递对原始对象的引用. Matlab可以使用只读引用机制来加快处理速度,但是该函数或方法不能更改原始对象的属性.
Normal objects are usually considered value
objects. When they are passed to a function or a method, only the value is passed not a reference to the original object. Matlab may use a read-only referencing mechanism to speed things up, but the function or method cannot change the properties of the original object.
要能够通过引用传递输入参数,您的自定义对象必须是handle
对象.只需在定义您的类时,从handle
继承,就可以达到目的:
To be able to pass an input parameter by reference, your custom object needs to be a handle
object. Simply when defining your class, inherit from handle
and that should do the trick:
classdef Person < handle
和
classdef Family < handle
这篇关于对象方法中的自引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!