2012-11-21 14 views
5

賦予下面的代碼:Matlab的等效於調用靜態類中

classdef highLowGame 
    methods(Static) 
     function [wonAmount, noGuesses] = run(gambledAmount) 
      noGuesses = 'something'; 
      wonAmount = highLowGame.getPayout(gambledAmount, noGuesses); % <--- 
     end 
     function wonAmount = getPayout(gambledAmount, noGuesses) 
      wonAmount = 'something'; 
     end 
    end 
end 

有沒有辦法來調用同一個類的靜態方法方法(靜態內部),而無需編寫的類名?就像「self.getPayout(...)」 - 如果類變成500行,我想重命名它。

回答

4

據我所知,「不」與「但」。通常,只能用類名指定靜態方法。但是,您可以假冒你的方式周圍的限制,因爲MATLAB具有feval:

classdef testStatic 

    methods (Static) 
     function p = getPi() %this is a static method 
      p = 3.14; 
     end 
    end 

    methods 
     function self = testStatic() 

      testStatic.getPi %these are all equivalent 
      feval(sprintf('%s.getPi',class(self))) 
      feval(sprintf('%s.getPi',mfilename('class'))) 
     end 
    end 
end 

這裏,類(個體經營)和mfilename都評價爲「testStatic」,所以上面結了評估「testStatic.getPi」的功能。或者,也可以編寫一個非靜態方法self.callStatic;然後總是使用它。在裏面,只需調用testStatic.getPi。那麼你只需要改變那一行。

+2

如果您在@ -folder定義的類中有單獨的函數,應該是'mfilename('class')''。 – Amro

+0

是的。完全正確。上面修改的答案。 – Pete

+4

仍然我寧願只寫一個類的名字,並且依賴一個好的編輯器來查找/替換,以防我需要重構。類名不是你期望經常改變的東西。 – Amro

7

不是直接回答您的問題,但值得注意的是,您也可以在classdef塊的末尾在class.m文件中放置「本地函數」,這些文件的行爲與私有靜態方法類似,但您不需要使用類名來調用它們。即

% myclass.m 
classdef myclass 
    methods (Static) 
    function x = foo() 
     x = iMyFoo(); 
    end 
    end 
end 
function x = iMyFoo() 
    x = rand(); 
end 
% end of myclass.m 
+0

在classdef結束後放置函數嗎?有趣的:) –