【发布时间】:2015-08-17 07:48:32
【问题描述】:
我正在编写一些 Matlab 代码来从特定文件格式加载数据,以便我可以以统一的方式处理加载的数据。
因此,我想使用一个抽象类来表示数据,该抽象类对于每种可能的文件格式都有唯一的子类。
我的方案的核心是一种从文件中获取数据的方法(实现的唯一位),或者如果数据已经加载,则将其吐出。 IE。一种延迟加载系统,因为从磁盘获取数据可能很慢......
我想在我的 Matlab 程序中设置一个抽象类,如下所示:
classdef TCSPCImageData
properties (SetAccess = protected)
% The same for all subclasses.
frameindex = -1;
framedata = '';
...
end
properties (Abstract, SetAccess = protected)
% Needs to be set by subclass
type
end
methods
% Constructor. Code omitted for brevity
function obj = TCSPCImageData(path)
...
end
function data = frame(obj, idx, tshift)
% Some shared functionality.
if (obj.frameindex == idx)
...
else
% Call a specific subclass method.
data = obj.getframe(idx,tshift);
end
end
end
methods (Abstract, Access = protected)
% The abstract method that will be implemented by each subclass.
getframe(obj, idx, tshift)
end
end
总而言之,我的超类中有一个方法,其功能是所有子类都应该共享的,但在该方法中,我称之为特定实现,每个子类都是唯一的。
然后一个子类是这样的:
classdef PTUImageData < Data.TCSPCImageData
properties (SetAccess = protected)
% Specific initialisation of this variable
type = 'PTU';
end
methods
% We call the superclass constructor.
function obj = PTUImageData(path)
obj@Data.TCSPCImageData(path);
end
% Apparently, you need to call the superclass method.
function data = frame(obj, idx, tshift)
data = frame@Data.TCSPCImageData(obj, idx, tshift);
end
end
methods(Access = protected)
% The specific implementation.
function data = getframe(obj, idx, tshift)
obj.framedata = 'some value';
end
end
end
天真地,我认为这应该很好用。
但是,obj.framedata = 'some value'; 只更新子类范围内的变量。像这样运行此代码时不会维护该值:
testdata = Data.PTUImageData('somepath');
testdata.frame(1,1);
在子类中设置断点表明 obj.framedata 已设置,但如果我稍后检查我的 testdata 对象,testdata.framedata 将为空,这是完全出乎意料的。
谁能告诉我我的方法的错误?
编辑
正如下面的答案所说,不需要显式调用frame 函数:
classdef PTUImageData < Data.TCSPCImageData
properties (SetAccess = protected)
% Specific initialisation of this variable
type = 'PTU';
end
methods
% We call the superclass constructor.
function obj = PTUImageData(path)
obj@Data.TCSPCImageData(path);
end
end
methods(Access = protected)
% The specific implementation.
function data = getframe(obj, idx, tshift)
obj.framedata = 'some value';
end
end
end
【问题讨论】:
标签: matlab oop abstract-class