2016-07-30 83 views
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)(行...) 輸入參數不足。 有什麼問題?

回答

2

首先,你不能有somemethod作爲方法屬性。您可以擺脫該方法,併爲您的構造函數中的屬性指定一個函數句柄。

function self = test(number) 
    self.number = number; 
    switch self.number 
     case 1 
      self.somemethod = @(obj)somemethod1(obj) 
    %.... 
    end 
end 

而且,當前的匿名函數你傳遞的對象的方法的副本:

  1. obj.method隱含通過obj作爲第一個輸入
  2. obj.method(obj)傳遞的第二個副本作爲第二輸入的obj

您想更新您的對象句柄,如下所示,它會將obj的單個副本傳遞給該方法。

obj.somemethod = @obj.somemethod3 

此外,使用你的類時,你就必須使用點符號,因爲它是一個屬性,而不是一個「真實」的方法

S = test() 
S.somemethod() 
+0

有關屬性和方法是相同的名稱來執行somemethod是我的類型錯誤(我的意思是在構造函數中初始化)。但'S = test(2); S.somemethod()'生成錯誤:「錯誤使用測試> @(obj)obj.somemethod2(obj)沒有足夠的輸入參數。」 –

+0

@AlexanderKorovin對不起,我打錯了。應該現在工作 – Suever

+0

謝謝!不幸的是,我發現這個實現('obj.somemethod = @ obj.somemethod3')比使用'switch'大約慢兩倍! –

相關問題