我想只为一个特定的类重载一种subsref调用('()'类型),并留下任何其他调用Matlab的内置子参考 - 具体来说,我希望Matlab通过处理属性/方法访问''类型。但是,当subsref在类中被重载时,似乎Matlab的'builtin'函数不起作用。为什么我不能使用内建函数来重载subsref?
考虑这个类:
classdef TestBuiltIn
properties
testprop = 'This is the built in method';
end
methods
function v = subsref(this, s)
disp('This is the overloaded method');
end
end
end
要使用重载的subsref方法,我这样做:
t = TestBuiltIn;
t.testprop
>> This is the overloaded method
这是符合市场预期。但是现在我想调用Matlab内置的subsref方法。为了确保我正确地做事,我首先尝试了类似的结构调用:
x.testprop = 'Accessed correctly';
s.type = '.';
s.subs = 'testprop';
builtin('subsref', x, s)
>> Accessed correctly
这也如预期的那样。但是,当我尝试在TestBuiltIn同样的方法:
builtin('subsref', t, s)
>> This is the overloaded method
... MATLAB调用重载的方法,而不是内置的方法。为什么Matlab在调用内置的方法时调用超载的方法?
更新: 对@Andrew Janke的回答,该解决方案几乎可行但不完全。考虑这个类:
classdef TestIndexing
properties
prop1
child
end
methods
function this = TestIndexing(n)
if nargin==0
n = 1;
end
this.prop1 = n;
if n<2
this.child = TestIndexing(n+1);
else
this.child = ['child on instance ' num2str(n)];
end
end
function v = subsref(this, s)
if strcmp(s(1).type, '()')
v = 'overloaded method';
else
v = builtin('subsref', this, s);
end
end
end
end
所有这一切的工作原理:
t = TestIndexing;
t(1)
>> overloaded method
t.prop1
>> 1
t.child
>> [TestIndexing instance]
t.child.prop1
>> 2
但是,这并不正常工作;它使用内置的subsref为孩子而不是超载的subsref:
t.child(1)
>> [TestIndexing instance]
注意上面的行为与这两种行为(这是如预期)的不一致:
tc = t.child;
tc(1)
>> overloaded method
x.child = t.child;
x.child(1)
>> overloaded method
不知道我是否完全理解,但我认为首先调用内置函数,然后在该调用中调用重载方法。如果可能的话,在有用点放置一个断点。 – 2013-04-24 18:40:17
完全不同的东西:我希望你只是为了个人兴趣去尝试这样做,因为对于大多数问题,重载subsref可能不是最好的解决方案。 – 2013-04-24 18:41:39
我不确定你首先调用的内建函数是什么意思 - 如果这是假设的情况(不知道如何,但说),我想我需要在Matlab的内置subsref函数内设置一个断点来验证。但是,这是一个本地函数,而不是一个m函数,所以我不能在那里放置一个断点。 – Ben 2013-04-24 19:26:07