如果我正确理解您的问题,听起来您希望您的新类 test 简单地继承为属性 x 的类定义的所有二进制和一元方法(并在属性 x 上操作调用它们),这样您就不必自己重新定义它们。
如果这是您想要的,那么我认为唯一可行的方法是实际使用 inheritance 并使您的类 test 成为属性类的 subclass x。考虑到x 只是double 的简单情况,可以在here 中找到一个继承内置double 类型的好例子。将该示例改编为您的示例,这是您可以实现类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
obj@double(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