2016-12-27 86 views
0

是否可以將函數附加到類型爲struct的類屬性?用法:將函數附加到Matlab結構

% Definition: 
classdef a < handle 
    properties 
    bar 
    end 
    methods 
    function obj = a() 
     obj.bar = struct; 
     %obj.bar.attachFunction('apply', @someFunction); <-- something like this 
    end 
    end 
end 

% Usage: 
foo = a(); 
foo.bar.apply('test'); 
foo.bar.var1 = 1; 
foo.bar.var2 = 2; 

回答

0

噢,那其實很簡單,只要我用了我的腦海。

classdef a < handle 
    properties 
    bar 
    end 
    methods 
    function obj = a() 
     obj.bar = struct; 
     obj.bar.apply = @(str) @obj.barApply(str); 
    end 
    end 
    methods (Access=protected) 
    function barApply(obj, str) 
     obj.bar.something = str; 
    end 
    end 
end 

foo = a(); 
foo.bar.apply('monkey'); 
foo.bar.apple = 2; 
+0

在這裏您將添加字段到一個對象的屬性,但我想你可能也有興趣添加動態屬性到一個實例。你可以在這裏閱讀它:https://www.mathworks.com/help/matlab/matlab_oop/dynamic-properties--adding-properties-to-an-instance.html –