chr*_*cow 3 matlab containers properties map matlab-class
我创建自己的类如下:
classdef testClass < handle
properties
value;
map = containers.Map('KeyType','double','ValueType','any');
end
end
Run Code Online (Sandbox Code Playgroud)
我的目标是为每个对象testClass
维护自己的地图.然而,事实证明,整个类只有一个地图对象:testClass
访问相同的所有对象containers.Map
.例如,如果我创建两个对象,如下所示
a = testClass;
b = testClass;
a.value = 'a';
b.value = 'b';
a.map(1) = 123;
b.map(2) = 321;
Run Code Online (Sandbox Code Playgroud)
它最终都是两个,a
并且b
地图包含两个键值对:
>> a
a =
testClass handle
Properties:
value: 'a'
map: [2x1 containers.Map]
>> b
b =
testClass handle
Properties:
value: 'b'
map: [2x1 containers.Map]
Methods, Events, Superclasses
Run Code Online (Sandbox Code Playgroud)
两个(键,值)对(1,123)和(2,321)都出现在a.map
和b.map
>> a.map.keys
ans =
[1] [2]
>> a.map.values
ans =
[123] [321]
>> b.map.keys
ans =
[1] [2]
>> b.map.values
ans =
[123] [321]
Run Code Online (Sandbox Code Playgroud)
这是一个错误吗?如何containers.Map
为每个类对象保持独立?
问题是不是testClass
一个handle
,而是在指定的初始值properties
块没有被评估时,你认为它是.MATLAB仅在加载类时计算类属性的默认值,然后将该值提供给类的每个新实例.
你可以通过查看你的元类来看到这一点testClass
.例如:
c = testClass;
c.map(1) = 42;
hc = ?testClass;
hc.PropertyList(2).DefaultValue.keys % returns [1]
hc.PropertyList(2).DefaultValue.values % returns [42]
Run Code Online (Sandbox Code Playgroud)
如果希望每个实例具有不同的映射,则必须在构造函数中显式构造映射.(是的,我去过那里,完成了).
归档时间: |
|
查看次数: |
588 次 |
最近记录: |