【发布时间】:2016-12-05 03:40:03
【问题描述】:
我正在尝试使用 MATLAB OOP。我想更改类构造函数中的类方法处理程序。
例如,我有一个类test,其中类方法使用取决于类属性中的变量number 的方法之一:
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
这里每当调用test.somemethod() 时都会使用switch 运算符。 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) (line ...)
输入参数不足。
怎么了?
【问题讨论】:
标签: matlab