我正在尝试创建一个与MATLAB 2017b中的Line对象的类相似的类,但析构函数有问题。我想与其他图形对象实现类似的行为,即删除该句柄时不再引用该对象,如以下示例所示:
>> l1 = line([0 1], [0 1]);
如果现在关闭了包含行l1
的图形,则该变量表明l1
引用了已删除的对象:
>> l1
l1 =
handle to deleted Line
我创建了以下课程:
classdef circle < handle ...
& matlab.mixin.CustomDisplay & matlab.mixin.SetGet
properties
Center = [];
Color = [0 0.4470 0.7410];
Radius = [];
end
properties (SetAccess = 'protected')
LineHandle = [];
end
methods
function obj = circle(radius, center, varargin)
if nargin > 0
% assign property values
obj.Radius = radius;
obj.Center = center;
% generate plotting variables
phi = linspace(0, 2*pi, 90);
x = radius*cos(phi) + center(1);
y = radius*sin(phi) + center(2);
% draw circle
obj.LineHandle = line(x, y);
% create listeners in line object
obj.createListener;
% set variable properties
for k = 1:2:length(varargin)
% set superclass properties
if (isprop(obj.LineHandle, varargin{k}))
set(obj.LineHandle, varargin{k},varargin{k+1});
if (isprop(obj, varargin{k}))
set(obj, varargin{k}, varargin{k+1});
end
end
end
end
end
% listener to invoke delete if line is closed
function createListener(obj)
set(obj.LineHandle,'DeleteFcn',...
@obj.delete);
end
function delete(obj,varargin)
disp('deleted')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% command to delete class ???
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
end
end
如果关闭了包含圆形对象的图形,则删除线,但圆形对象仍然存在。有没有办法删除对圆对象的引用?
答案 0 :(得分:0)
我自己找到了答案。该函数只需要使用与delete不同的名称即可:
function delete_obj(obj, varargin)
% delete handle
delete(obj)
end