好的,所以我有一个父类MOM
与一堆属性SetAccess属性设置为protected
。它有一个特殊的静态方法setProperty
来设置它的属性:
classdef MOM < handle
properties (SetAccess = 'protected')
age;
occupation;
num_kids;
MOMmusthaves ={'age','occupation','num_kids'};
end
methods
function obj = MOM(varargin)
if iscell(varargin{1,1})
varargin =varargin{1,1};
end
inputstrings=varargin(cellfun(@isstring,varargin)); % get strings out of the inputs
if(isempty(setxor(intersect(inputstrings,obj.MOMmusthaves),obj.MOMmusthaves)))
% if all proper inputs are entered, initialize your object
for pp =1:length(obj.MOMmusthaves)
obj.setProperty(obj,varargin,obj.MOMmusthaves{pp});%find each input in the vararagins, and set it
end
else
display('Hey! These inputs are wrong. type help MOM for an example. Make sure you inlcude inputs for all of the following:'); obj.MOMmusthaves
return;
end
end
end
methods (Static)
function setProperty(obj,varargs,xx)
eval(sprintf('obj.%s = varargs{find(strcmp(''%s'',varargs))+1};',xx,xx));
end
end
end
然后我有一个子对象KID
,它有更多的属性,也SetAccess protected
。当我尝试使用MOM
的静态方法在KID
的构造函数内设置KID
属性时,我得到一个错误:(错误提示:
不能设置KID的只读属性'allowance'。
基本上,似乎KID
不认为它可以使用MOM
的静态方法作为自己的(所以没有正确继承它)。
我的问题是:是否有任何方法可以使静态方法被回收并可用于KID自己受保护的属性?
仅供参考,这是KID
代码;
classdef KID < MOM
properties (SetAccess = 'protected')
gender;
allowance;
favoritecandy;
KIDmusthaves ={'gender','allowance','favoritecandy'};
end
methods
function obj = KID(varargin)
obj = obj@MOM(varargin(:)); % Special construct for instantiating the superclass
inputstrings=varargin(cellfun(@isstring,varargin)); % get strings out of the inputs.
if(isempty(setxor(intersect(inputstrings,obj.KIDmusthaves),obj.KIDmusthaves)))
% if all proper inputs are entered, initialize your object
for pp =1:length(obj.KIDmusthaves)
%find each input in the vararagins, and set it
obj.setProperty(obj,varargin,obj.KIDmusthaves{pp});
end
else
display('please use correct input format. Make sure you include inputs for all of the following:');
obj.KIDmusthaves
return;
end
end
end
end
我不确定错误的确切来源是什么;虽然,我认为这可能是由于被eval
隐藏的句柄对象的突变。
无论如何,如果我理解setProperty
的预期用法,我认为使用点符号(类似于结构体的动态字段名称)以非static
形式编写函数可能是最简单的:
methods
function [] = setProperty(obj,musthaves,varargin)
keys = varargin(1:2:end);
values = varargin(2:2:end);
for pp =1:length(keys)
key = keys{k};
if any(strcmp(musthaves,key))
obj.(key) = values{pp};
end
end
end
end
其中musthaves
是任何属性字符串的单元格数组你也可以让musthaves
是一个字符串,表示obj
属性包含属性列表:
methods
function [] = setProperty(obj,musthaves,varargin)
keys = varargin(1:2:end);
values = varargin(2:2:end);
for pp =1:length(keys)
key = keys{k};
if any(strcmp(obj.(musthaves),key))
obj.(key) = values{pp};
end
end
end
end