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'大約慢兩倍! –