【发布时间】:2015-08-19 09:18:14
【问题描述】:
我正在尝试使用 MATLAB OOP 功能为网格开发数据结构。长话短说,我正在修改一个实例的字段,该实例继承自与另一个实例相同的基类,并且两个实例都被修改,就好像该字段被声明为静态一样!
我在 MATLAB 的抽象基类 (m_element) 中有这段代码:
properties(Access = protected)
nodes = containers.Map('KeyType','int64', 'ValueType', 'any');
faces = containers.Map('KeyType','int64', 'ValueType', 'any');
end
这些字段表示每个元素的连接性。例如,哪些节点是第 n 个节点的邻居,或者哪些面与第 n 个节点相邻。
我还有另外两个类:m_face 和 m_node,每一个都继承自 m_element。 m_node 很简单:
classdef m_node < m_element
properties
x = 0;
y = 0;
z = 0;
end
methods
function node = m_node(gmsh_id, x, y, z)
node = node@m_element(gmsh_id);
node.x = x;
node.y = y;
node.z = z;
end
end
end
但是当谈到 m_face 时,我遇到了一个问题。这是出现问题的构造函数:
function face = m_face(varargin)
face = face@m_element(varargin{1});
for k = 2:nargin
nod = varargin{k};
if(~isa(nod, 'm_node'))
error('Algum dos argumentos não é um node!');
elseif (~isvalid(nod))
error('Algum dos argumentos não é válido!');
else
face.nodes(nod.gmsh_id) = nod;
nod.faces(face.gmsh_id) = face;
end
end
end
m_face 构造函数期望人脸 ID 作为第一个参数,其余的应该是构成人脸的节点。 face.nodes(nod.gmsh_id) = nod; 似乎是我的问题所在。我有一个 m_mesh 类,它应该包含每个节点和面:
classdef m_mesh < handle
properties(SetAccess = private)
nodes = containers.Map('KeyType','int64', 'ValueType', 'any');
faces = containers.Map('KeyType','int64', 'ValueType', 'any');
end
methods
function theMesh = m_mesh(msh)
for idx = 1:numel(msh.POS(:,1))
n = msh.POS(idx,:);
theMesh.nodes(idx) = m_node(idx, n(1), n(2), n(3));
end
for idx = 1:numel(msh.TRIANGLES(:,1))
ele = msh.TRIANGLES(idx,:);
nod(1) = theMesh.nodes(ele(1));
nod(2) = theMesh.nodes(ele(2));
nod(3) = theMesh.nodes(ele(3));
theMesh.faces(idx) = m_face(idx, nod(1), nod(2), nod(3));
end
end
end
end
构造函数的msh 参数保存节点空间位置,以及组成每个面的节点(在本例中为三角形)。
这是我构建网格时得到的结果:
>> mesh = m_mesh(m)
mesh =
m_mesh with properties:
nodes: [5x1 containers.Map]
edges: [0x1 containers.Map]
faces: [4x1 containers.Map]
>> nod = mesh.nodes.values();
>> nod{1}.i_nodes
ans =
[1x1 m_node] [1x1 m_node] [1x1 m_node] [1x1 m_node] [1x1 m_node]
i_nodes 返回实例映射值。现在,这怎么可能?如果我还没有设置,为什么我的第一个(以及所有其他!)节点有五个相邻节点?当我从随机实例访问该字段时,MATLAB 为什么要更改所有实例和所有子类的非静态字段?
【问题讨论】:
标签: matlab oop inheritance