【发布时间】:2017-05-07 10:20:24
【问题描述】:
这是一个糟糕的标题,但让我试着解释一下。我有一个类test_class,可以通过以下两种方式之一构建。我可以通过调用test_obj = test_class 创建一个具有默认属性的对象,或者我可以通过调用test_obj_array = test_class([x,y]) 创建一个具有默认属性的对象数组。这是完整的代码:
classdef test_class
properties
A;
end
properties (Dependent = true)
B;
end
methods
function obj = test_class(S)
if nargin == 0
obj.A = 1;
else
x = size(S,1);
y = size(S,2);
obj(x,y) = test_class;
end
function B_value = get.B(obj)
B_value = obj.A * 2;
end
end
end
现在,当我检查这些对象的属性时:
test_obj_array(1,1).A = []
test_obj_array(1,1).B = []
test_obj_array(1,2).A = 1
test_obj_array(1,2).B = 2
...
为什么没有构造数组中的第一个对象?
现在,通过添加test_obj_array(1,1) = test_class 或稍后修改属性很容易修复,但这是一件容易忘记且难以排除故障的事情。
注意:如果将值数组传递给构造函数,则不会看到此行为,如 MATLAB documentation 中所示。
【问题讨论】:
-
它没有被构造,因为你从未指示 MATLAB 这样做。通过传递输入参数,您可以绕过数组中第一个对象的无参数构造函数。你打算
[x,y]是什么?输出对象数组的大小?
标签: arrays matlab oop constructor