1
我正在尝试使用MATLAB OOP。我想更改类构造函数中的类方法处理程序。 例如,我有一个类test
其中一类方法使用的取决于可变number
类性质的方法之一:是否有可能在MATLAB中改变方法功能处理程序classdef
mytest = test(2);
mytest.somemethod();
classdef test < handle
properties
number
end
methods
function obj = test(number)
obj.number = number;
end
function obj = somemethod(obj)
switch obj.number
case 1
obj.somemethod1();
case 2
obj.somemethod2();
case 3
obj.somemethod3();
end
end
function obj = somemethod1(obj)
fprintf('1')
end
function obj = somemethod2(obj)
fprintf('2')
end
function obj = somemethod3(obj)
fprintf('3')
end
end
end
这里使用switch
操作者每当test.somemethod()
被调用。我可以使用switch
曾经只在类的构造函数初始化的时间(即改变方法处理)如下:
classdef test < handle
properties
number
somemethod %<--
end
methods
% function obj = somemethod(obj,number) % my mistake: I meant the constructor
function obj = test(number)
obj.number = number;
switch number
case 1
obj.somemethod = @(obj) obj.somemethod1(obj);
case 2
obj.somemethod = @(obj) obj.somemethod2(obj);
case 3
obj.somemethod = @(obj) obj.somemethod3(obj);
end
end
function obj = somemethod1(obj)
fprintf('1')
end
function obj = somemethod2(obj)
fprintf('2')
end
function obj = somemethod3(obj)
fprintf('3')
end
end
end
这第二个实施test
类不起作用。 对于S = test(2); S.somemethod()
,出现错误: 错误使用测试> @(obj)obj.somemethod2(obj)(行...) 输入参数不足。 有什么问题?
有关属性和方法是相同的名称来执行
somemethod
是我的类型错误(我的意思是在构造函数中初始化)。但'S = test(2); S.somemethod()'生成错误:“错误使用测试> @(obj)obj.somemethod2(obj)没有足够的输入参数。” –@AlexanderKorovin对不起,我打错了。应该现在工作 – Suever
谢谢!不幸的是,我发现这个实现('obj.somemethod = @ obj.somemethod3')比使用'switch'大约慢两倍! –