如果我明白你的問題的權利,這聽起來像你希望你的新類test
簡單地繼承所有的該類物業x
定義的二元和一元方法(和調用它們時,物業x
操作),以便你不必自己重新定義它們。
如果這是你想要的,那麼我認爲,唯一可行的辦法做這樣的事情是實際使用繼承,讓您的test
類的類的屬性x
的subclass。考慮到x
只是double
的簡單情況,可以找到類型的子類別的一個很好的示例here。適應這個例子給你,這裏是你可以實現你的類test
一個辦法:
classdef test < double
properties
p
end
methods
function obj = test(x, p)
if (nargin < 2)
p = 0;
if (nargin < 1)
x = 0;
end
end
[email protected](x);
obj.p = p;
end
function sref = subsref(obj, s)
switch s(1).type
case '.'
switch s(1).subs
case 'p'
sref = obj.p;
case 'x'
x = double(obj);
if (length(s) < 2)
sref = x;
elseif (length(s) > 1) && strcmp(s(2).type, '()')
sref = subsref(x, s(2:end));
end
otherwise
error('Not a supported indexing expression')
end
case '()'
x = double(obj);
newx = subsref(x, s(1:end));
sref = test(newx, obj.p);
case '{}'
error('Not a supported indexing expression')
end
end
function obj = subsasgn(obj, s, b)
switch s(1).type
case '.'
switch s(1).subs
case 'p'
obj.p = b;
case 'x'
if (length(s) < 2)
obj = test(b, obj.p);
elseif (length(s) > 1) && strcmp(s(2).type, '()')
x = double(obj);
newx = subsasgn(x, s(2:end), b);
obj = test(newx, obj.p);
end
otherwise
error('Not a supported indexing expression')
end
case '()'
x = double(obj);
newx = subsasgn(x, s(1), b);
obj = test(newx, obj.p);
case '{}'
error('Not a supported indexing expression')
end
end
function disp(obj)
fprintf('p:');
disp(obj.p);
fprintf('x:');
disp(double(obj));
end
end
end
有一點需要注意:您使用的test
類的對象double
運算符和方法會返回double
類的結果得到的結果,只要你願意,不是test
。爲了得到你想要的,你必須將結果重新分配每次財產x
,如下面的例子行爲:
>> a = test(1:3, pi) % Create an object with p = pi, and x = [1 2 3]
a =
p: 3.141592653589793
x: 1 2 3
>> a.x = -a % Unary operation on a, and reassignment to x
a =
p: 3.141592653589793
x: -1 -2 -3
>> a.x = a+4 % Binary operation and reassignment
a =
p: 3.141592653589793
x: 3 2 1
>> a.x = mean(a) % Another unary operation and reassignment
a =
p: 3.141592653589793
x: 2
也許這類似的帖子能幫助你:https://www.mathworks.com/matlabcentral/answers/275199 - 如何重載所有功能和運營商的新課程 – kpg987
是的,我在寫問題之前檢查過。編寫'S0.oper(@plus,(S2.oper(@minus,(S0.oper(@abs)))))'或類似的簡單算術運算的類,而不是'S0 + S2-abs(S0)'...... – hyprfrcb
你提到「繼承」。這是否意味着'test'是一個包含'x'的類的子類?如果是這樣,那個超類是否實現了任何內置的運算符? – gnovice