How to make objects of the same class have independent containers.Map member?

2 次查看(过去 30 天)
I create my own class as below:
classdef testClass < handle
properties
value;
map = containers.Map('KeyType','double','ValueType','any');
end
end
My goal is for each object of testClass to maintain its own map. However, it turns out that there is only one map object that for the whole class: all objects of testClass access to the same containers.Map. For example, if I create two objects as follows
a = testClass;
b = testClass;
a.value = 'a';
b.value = 'b';
a.map(1) = 123;
b.map(2) = 321;
It ends up both a and b's map contains two key-value pairs:
>> 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
Both (key,value) pairs (1,123) and (2,321) appears in both a.map and 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]
Is this a bug? How can I keep independent containers.Map for each class object??

采纳的回答

Peter Perkins
Peter Perkins 2013-10-3
Guanfeng, the problem is that you're initializing the map property in the properties block, and the value you're initializing with is a handle. Your class creates the value on the right hand side of
map = containers.Map('KeyType','double','ValueType','any');
once, and assigns it to that property in each new instance. But because that value is a handle, the assignment just copies the handle, and so all the properties point to the same map. This would not happen if you initialized with a value that wasn't a handle.
The solution is to put the initialization of that property into the testClass constructor.
Hope this helps.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Class File Organization 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by