抱歉,格式错误,我粘贴并应用了{}控件,但它看起来仍然损坏。如果我以某种方式误用了这个工具,请告诉我。
我有一个基类:
classdef SystemNode < matlab.mixin.Heterogeneous
properties (Abstract)
description
quantity
parent
unit_cost
learning_curve
average_cost
total_cost
children
end
end我有一个后代:
classdef Subsystem < models.system.SystemNode
properties
description
quantity
parent
children
key
end
properties (Dependent)
unit_cost
learning_curve
average_cost
total_cost
end
methods
function self = Subsystem(description, quantity, parent)
% TODO: Validate Inputs
self.description = description;
self.quantity = quantity;
self.parent = parent;
self.children = [];
self.key = char(java.util.UUID.randomUUID().toString());
end
function add_child(self, node)
% TODO: Validate Inputs
self.children = [self.children node];
end
function unit_cost = get.unit_cost(self)
% Cost if there were only one.
unit_cost = 0;
for child = self.children
unit_cost = child.unit_cost;
end
unit_cost = unit_cost*self.quantity;
end
function learning_curve = get.learning_curve(self)
learning_curve = 0;
end我不能让.add_child()工作。例如:
>> ss = models.system.Subsystem('test', 1, []);
>> ss.add_child('a')
>> ss.children
ans =
[]如果我从handle而不是Mixin继承我的抽象类,这会工作得很好。我做错了什么??
顺便说一句。我正在使用Matlab 2011b
提前谢谢。
发布于 2013-04-26 06:20:34
handle使对象以按引用传递的方式运行。如果您想要这种行为,请尝试以下操作:
classdef SystemNode < matlab.mixin.Heterogeneous & handle如果不是从handle继承,就会得到正常的Matlab值传递行为。在这种情况下,如果要更新对象的状态,则必须从setter方法返回更新的对象,并存储返回的更新值。
所以setter必须返回更新后的self。
function self = add_child(self, node)
self.children = [self.children node];
end并且对它的调用存储返回的更新对象。
ss = ss.add_child('a')如果您没有在ss中存储新的值,那么您仍然会看到add_child调用之前的ss的值,没有子级。
https://stackoverflow.com/questions/16225489
复制相似问题