adg*_*teq 3 matlab operator-overloading
我在MATLAB中编写了一个简单的类来管理一组键值对.我希望能够在对象名称之后使用点来访问键,如:
params.maxIterations
Run Code Online (Sandbox Code Playgroud)
代替:
params.get('maxIterations')
Run Code Online (Sandbox Code Playgroud)
是否可以覆盖点运算符,以便调用我的get()方法?
我试图覆盖这里建议的subsasgn()方法,但我无法弄清楚我应该如何编写它.
您可以使用动态属性.然后,不是添加字符串列表,而是为每个"键"添加新属性.得到所有的钥匙properties(MyClass)
(只是fieldnames(MyClass)
然而,我认为最好超载subsref
,但请注意, 如果你第一次这样做的话,正确地做这件事可能会耗费大部分工作周......这并不是说它真的很难,只是()
操作员这样做了多:)
幸运的是,你没必要.这是如何做:
classdef MyClass < handle
methods
function result = subsref(obj, S)
%// Properly overloading the () operator is *DIFFICULT*!!
%// Therefore, delegate everything to the built-in function,
%// except for 1 isolated case:
try
if ~strcmp(S.type, '()') || ...
~all(cellfun('isclass', S.subs, 'char'))
result = builtin('subsref', obj, S);
else
keys = S.subs %// Note: cellstring;
%// could contain multiple keys
%// ...and do whatever you want with it
end
catch ME
%// (this construction makes it less apparent that the
%// operator was overloaded)
throwAsCaller(ME);
end
end % subsref method
end % methods
end % class
Run Code Online (Sandbox Code Playgroud)